@vnxjs/helper
Version:
Vnmf Helper
661 lines • 25.1 kB
JavaScript
;
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readConfig = exports.readPageConfig = exports.removeHeadSlash = exports.getModuleDefaultExport = exports.addPlatforms = exports.extnameExpRegOf = exports.readDirWithFileTypes = exports.getAllFilesInFolder = exports.unzip = exports.applyArrayedVisitors = exports.mergeVisitors = exports.recursiveMerge = exports.getInstalledNpmPkgVersion = exports.getInstalledNpmPkgPath = exports.pascalCase = exports.emptyDirectory = exports.cssImports = exports.generateConstantsList = exports.generateEnvList = exports.resolveScriptPath = exports.resolveMainFilePath = exports.isEmptyObject = exports.shouldUseCnpm = exports.shouldUseYarn = exports.getSystemUsername = exports.getConfig = exports.getVnmfPath = exports.getUserHomeDir = exports.recursiveFindNodeModules = exports.printLog = exports.resolveStylePath = exports.promoteRelativePath = exports.replaceAliasPath = exports.isAliasPath = exports.isQuickAppPkg = exports.isNpmPkg = exports.isNodeModule = exports.normalizePath = void 0;
const child_process = __importStar(require("child_process"));
const fs = __importStar(require("fs-extra"));
const lodash_1 = require("lodash");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const constants_1 = require("./constants");
const swcRegister_1 = __importStar(require("./swcRegister"));
const terminal_1 = require("./terminal");
const execSync = child_process.execSync;
function normalizePath(path) {
return path.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
}
exports.normalizePath = normalizePath;
const isNodeModule = (filename) => constants_1.NODE_MODULES_REG.test(filename);
exports.isNodeModule = isNodeModule;
function isNpmPkg(name) {
if (/^(\.|\/)/.test(name)) {
return false;
}
return true;
}
exports.isNpmPkg = isNpmPkg;
function isQuickAppPkg(name) {
return /^@(system|service)\.[a-zA-Z]{1,}/.test(name);
}
exports.isQuickAppPkg = isQuickAppPkg;
function isAliasPath(name, pathAlias = {}) {
const prefixs = Object.keys(pathAlias);
if (prefixs.length === 0) {
return false;
}
return prefixs.includes(name) || (new RegExp(`^(${prefixs.join('|')})/`).test(name));
}
exports.isAliasPath = isAliasPath;
function replaceAliasPath(filePath, name, pathAlias = {}) {
// Follow-up path.join The real path will be parsed when the symlink is encountered,If...
// Here. filePath I didn't do the same thing.,It could lead to... import Point
// Source File,Could not close temporary folder: %s
filePath = fs.realpathSync(filePath);
const prefixs = Object.keys(pathAlias);
if (prefixs.includes(name)) {
return promoteRelativePath(path.relative(filePath, fs.realpathSync(resolveScriptPath(pathAlias[name]))));
}
const reg = new RegExp(`^(${prefixs.join('|')})/(.*)`);
name = name.replace(reg, function (_m, $1, $2) {
return promoteRelativePath(path.relative(filePath, path.join(pathAlias[$1], $2)));
});
return name;
}
exports.replaceAliasPath = replaceAliasPath;
function promoteRelativePath(fPath) {
const fPathArr = fPath.split(path.sep);
let dotCount = 0;
fPathArr.forEach(item => {
if (item.indexOf('..') >= 0) {
dotCount++;
}
});
if (dotCount === 1) {
fPathArr.splice(0, 1, '.');
return fPathArr.join('/');
}
if (dotCount > 1) {
fPathArr.splice(0, 1);
return fPathArr.join('/');
}
return normalizePath(fPath);
}
exports.promoteRelativePath = promoteRelativePath;
function resolveStylePath(p) {
const realPath = p;
const removeExtPath = p.replace(path.extname(p), '');
const vnmfEnv = process.env.VNMF_ENV;
for (let i = 0; i < constants_1.CSS_EXT.length; i++) {
const item = constants_1.CSS_EXT[i];
if (vnmfEnv) {
if (fs.existsSync(`${removeExtPath}.${vnmfEnv}${item}`)) {
return `${removeExtPath}.${vnmfEnv}${item}`;
}
}
if (fs.existsSync(`${p}${item}`)) {
return `${p}${item}`;
}
}
return realPath;
}
exports.resolveStylePath = resolveStylePath;
function printLog(type, tag, filePath) {
const typeShow = constants_1.processTypeMap[type];
const tagLen = tag.replace(/[\u0391-\uFFE5]/g, 'aa').length;
const tagFormatLen = 8;
if (tagLen < tagFormatLen) {
const rightPadding = new Array(tagFormatLen - tagLen + 1).join(' ');
tag += rightPadding;
}
const padding = '';
filePath = filePath || '';
if (typeof typeShow.color === 'string') {
console.log(terminal_1.chalk[typeShow.color](typeShow.name), padding, tag, padding, filePath);
}
else {
console.log(typeShow.color(typeShow.name), padding, tag, padding, filePath);
}
}
exports.printLog = printLog;
function recursiveFindNodeModules(filePath, lastFindPath) {
const findWorkspaceRoot = require('find-yarn-workspace-root');
if (lastFindPath && (normalizePath(filePath) === normalizePath(lastFindPath))) {
return filePath;
}
const dirname = path.dirname(filePath);
const workspaceRoot = findWorkspaceRoot(dirname);
const nodeModules = path.join(workspaceRoot || dirname, 'node_modules');
if (fs.existsSync(nodeModules)) {
return nodeModules;
}
if (dirname.split(path.sep).length <= 1) {
printLog("error" /* processTypeEnum.ERROR */, `Yes.${dirname}Under Contents`, 'Not foundnode_modulesFolder,Please install the Reliance Library first.!');
return nodeModules;
}
return recursiveFindNodeModules(dirname, filePath);
}
exports.recursiveFindNodeModules = recursiveFindNodeModules;
function getUserHomeDir() {
function homedir() {
const env = process.env;
const home = env.HOME;
const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
if (process.platform === 'win32') {
return env.USERPROFILE || '' + env.HOMEDRIVE + env.HOMEPATH || home || '';
}
if (process.platform === 'darwin') {
return home || (user ? '/Users/' + user : '');
}
if (process.platform === 'linux') {
return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : ''));
}
return home || '';
}
return typeof os.homedir === 'function' ? os.homedir() : homedir();
}
exports.getUserHomeDir = getUserHomeDir;
function getVnmfPath() {
const vnmfPath = path.join(getUserHomeDir(), constants_1.VNMF_CONFIG_FOLDER);
if (!fs.existsSync(vnmfPath)) {
fs.ensureDirSync(vnmfPath);
}
return vnmfPath;
}
exports.getVnmfPath = getVnmfPath;
function getConfig() {
const configPath = path.join(getVnmfPath(), 'config.json');
if (fs.existsSync(configPath)) {
return require(configPath);
}
return {};
}
exports.getConfig = getConfig;
function getSystemUsername() {
const userHome = getUserHomeDir();
const systemUsername = process.env.USER || path.basename(userHome);
return systemUsername;
}
exports.getSystemUsername = getSystemUsername;
function shouldUseYarn() {
try {
execSync('yarn --version', { stdio: 'ignore' });
return true;
}
catch (e) {
return false;
}
}
exports.shouldUseYarn = shouldUseYarn;
function shouldUseCnpm() {
try {
execSync('cnpm --version', { stdio: 'ignore' });
return true;
}
catch (e) {
return false;
}
}
exports.shouldUseCnpm = shouldUseCnpm;
function isEmptyObject(obj) {
if (obj == null) {
return true;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
exports.isEmptyObject = isEmptyObject;
function resolveMainFilePath(p, extArrs = constants_1.SCRIPT_EXT) {
const realPath = p;
const vnmfEnv = process.env.VNMF_ENV;
for (let i = 0; i < extArrs.length; i++) {
const item = extArrs[i];
if (vnmfEnv) {
if (fs.existsSync(`${p}.${vnmfEnv}${item}`)) {
return `${p}.${vnmfEnv}${item}`;
}
if (fs.existsSync(`${p}${path.sep}index.${vnmfEnv}${item}`)) {
return `${p}${path.sep}index.${vnmfEnv}${item}`;
}
if (fs.existsSync(`${p.replace(/\/index$/, `.${vnmfEnv}/index`)}${item}`)) {
return `${p.replace(/\/index$/, `.${vnmfEnv}/index`)}${item}`;
}
}
if (fs.existsSync(`${p}${item}`)) {
return `${p}${item}`;
}
if (fs.existsSync(`${p}${path.sep}index${item}`)) {
return `${p}${path.sep}index${item}`;
}
}
return realPath;
}
exports.resolveMainFilePath = resolveMainFilePath;
function resolveScriptPath(p) {
return resolveMainFilePath(p);
}
exports.resolveScriptPath = resolveScriptPath;
function generateEnvList(env) {
const res = {};
if (env && !isEmptyObject(env)) {
for (const key in env) {
try {
res[`process.env.${key}`] = JSON.parse(env[key]);
}
catch (err) {
res[`process.env.${key}`] = env[key];
}
}
}
return res;
}
exports.generateEnvList = generateEnvList;
function generateConstantsList(constants) {
const res = {};
if (constants && !isEmptyObject(constants)) {
for (const key in constants) {
if ((0, lodash_1.isPlainObject)(constants[key])) {
res[key] = generateConstantsList(constants[key]);
}
else {
try {
res[key] = JSON.parse(constants[key]);
}
catch (err) {
res[key] = constants[key];
}
}
}
}
return res;
}
exports.generateConstantsList = generateConstantsList;
function cssImports(content) {
let match;
const results = [];
content = String(content).replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '');
while ((match = constants_1.CSS_IMPORT_REG.exec(content))) {
results.push(match[2]);
}
return results;
}
exports.cssImports = cssImports;
/*eslint-disable*/
const retries = (process.platform === 'win32') ? 100 : 1;
function emptyDirectory(dirPath, opts = { excludes: [] }) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach(file => {
const curPath = path.join(dirPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
let removed = false;
let i = 0; // retry counter
do {
try {
if (!opts.excludes.length || !opts.excludes.some(item => curPath.indexOf(item) >= 0)) {
emptyDirectory(curPath);
fs.rmdirSync(curPath);
}
removed = true;
}
catch (e) {
}
finally {
if (++i < retries) {
continue;
}
}
} while (!removed);
}
else {
fs.unlinkSync(curPath);
}
});
}
}
exports.emptyDirectory = emptyDirectory;
/* eslint-enable */
const pascalCase = (str) => str.charAt(0).toUpperCase() + (0, lodash_1.camelCase)(str.substr(1));
exports.pascalCase = pascalCase;
function getInstalledNpmPkgPath(pkgName, basedir) {
const resolvePath = require('resolve');
try {
return resolvePath.sync(`${pkgName}/package.json`, { basedir });
}
catch (err) {
return null;
}
}
exports.getInstalledNpmPkgPath = getInstalledNpmPkgPath;
function getInstalledNpmPkgVersion(pkgName, basedir) {
const pkgPath = getInstalledNpmPkgPath(pkgName, basedir);
if (!pkgPath) {
return null;
}
return fs.readJSONSync(pkgPath).version;
}
exports.getInstalledNpmPkgVersion = getInstalledNpmPkgVersion;
const recursiveMerge = (src, ...args) => {
return (0, lodash_1.mergeWith)(src, ...args, (value, srcValue) => {
const typeValue = typeof value;
const typeSrcValue = typeof srcValue;
if (typeValue !== typeSrcValue)
return;
if (Array.isArray(value) && Array.isArray(srcValue)) {
return value.concat(srcValue);
}
if (typeValue === 'object') {
return (0, exports.recursiveMerge)(value, srcValue);
}
});
};
exports.recursiveMerge = recursiveMerge;
const mergeVisitors = (src, ...args) => {
const validFuncs = ['exit', 'enter'];
return (0, lodash_1.mergeWith)(src, ...args, (value, srcValue, key, object, srcObject) => {
if (!object.hasOwnProperty(key) || !srcObject.hasOwnProperty(key)) {
return undefined;
}
const shouldMergeToArray = validFuncs.indexOf(key) > -1;
if (shouldMergeToArray) {
return (0, lodash_1.flatMap)([value, srcValue]);
}
const [newValue, newSrcValue] = [value, srcValue].map(v => {
if (typeof v === 'function') {
return {
enter: v
};
}
else {
return v;
}
});
return (0, exports.mergeVisitors)(newValue, newSrcValue);
});
};
exports.mergeVisitors = mergeVisitors;
const applyArrayedVisitors = obj => {
let key;
for (key in obj) {
const funcs = obj[key];
if (Array.isArray(funcs)) {
obj[key] = (astPath, ...args) => {
funcs.forEach(func => {
func(astPath, ...args);
});
};
}
else if (typeof funcs === 'object') {
(0, exports.applyArrayedVisitors)(funcs);
}
}
return obj;
};
exports.applyArrayedVisitors = applyArrayedVisitors;
function unzip(zipPath) {
const Transform = require('stream').Transform;
const yauzl = require('yauzl');
return new Promise((resolve, reject) => {
yauzl.open(zipPath, { lazyEntries: true }, (err, zipfile) => {
if (err || !zipfile)
throw err;
zipfile.on('close', () => {
fs.removeSync(zipPath);
resolve();
});
zipfile.readEntry();
zipfile.on('error', (err) => {
reject(err);
});
zipfile.on('entry', entry => {
if (/\/$/.test(entry.fileName)) {
const fileNameArr = entry.fileName.replace(/\\/g, '/').split('/');
fileNameArr.shift();
const fileName = fileNameArr.join('/');
fs.ensureDirSync(path.join(path.dirname(zipPath), fileName));
zipfile.readEntry();
}
else {
zipfile.openReadStream(entry, (err, readStream) => {
if (err || !readStream)
throw err;
const filter = new Transform();
filter._transform = function (chunk, _encoding, cb) {
cb(undefined, chunk);
};
filter._flush = function (cb) {
cb();
zipfile.readEntry();
};
const fileNameArr = normalizePath(entry.fileName).split('/');
fileNameArr.shift();
const fileName = fileNameArr.join('/');
const writeStream = fs.createWriteStream(path.join(path.dirname(zipPath), fileName));
writeStream.on('close', () => { });
readStream
.pipe(filter)
.pipe(writeStream);
});
}
});
});
});
}
exports.unzip = unzip;
const getAllFilesInFolder = (folder, filter = []) => __awaiter(void 0, void 0, void 0, function* () {
let files = [];
const list = readDirWithFileTypes(folder);
yield Promise.all(list.map((item) => __awaiter(void 0, void 0, void 0, function* () {
const itemPath = path.join(folder, item.name);
if (item.isDirectory) {
const _files = yield (0, exports.getAllFilesInFolder)(itemPath, filter);
files = [...files, ..._files];
}
else if (item.isFile) {
if (!filter.find(rule => rule === item.name))
files.push(itemPath);
}
})));
return files;
});
exports.getAllFilesInFolder = getAllFilesInFolder;
function readDirWithFileTypes(folder) {
const list = fs.readdirSync(folder);
const res = list.map(name => {
const stat = fs.statSync(path.join(folder, name));
return {
name,
isDirectory: stat.isDirectory(),
isFile: stat.isFile()
};
});
return res;
}
exports.readDirWithFileTypes = readDirWithFileTypes;
function extnameExpRegOf(filePath) {
return new RegExp(`${path.extname(filePath)}$`);
}
exports.extnameExpRegOf = extnameExpRegOf;
function addPlatforms(platform) {
const upperPlatform = platform.toLocaleUpperCase();
if (constants_1.PLATFORMS[upperPlatform])
return;
constants_1.PLATFORMS[upperPlatform] = platform;
}
exports.addPlatforms = addPlatforms;
const getModuleDefaultExport = exports => exports.__esModule ? exports.default : exports;
exports.getModuleDefaultExport = getModuleDefaultExport;
function removeHeadSlash(str) {
return str.replace(/^(\/|\\)/, '');
}
exports.removeHeadSlash = removeHeadSlash;
function analyzeImport(filePath) {
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const code = fs.readFileSync(filePath).toString();
let importPaths = [];
filePath = path.dirname(filePath);
const ast = parser.parse(code, {
sourceType: 'module',
plugins: [
'typescript',
'classProperties',
'objectRestSpread',
'optionalChaining'
]
});
traverse(ast, {
ImportDeclaration({ node }) {
const list = [];
const source = node.source.value;
if (path.extname(source)) {
const importPath = path.resolve(filePath, source);
list.push(importPath);
}
else {
['.js', '.ts', '.json'].forEach(ext => {
const importPath = path.resolve(filePath, source + ext);
list.push(importPath);
});
}
const dep = list.find(importPath => fs.existsSync(importPath));
if (!dep)
return;
importPaths.push(dep);
if (path.extname(dep) !== '.json') {
importPaths = importPaths.concat(analyzeImport(dep));
}
}
});
return importPaths;
}
// converts ast nodes to js object
function exprToObject(node) {
const types = ['BooleanLiteral', 'StringLiteral', 'NumericLiteral'];
if (types.includes(node.type)) {
return node.value;
}
if (node.name === 'undefined' && !node.value) {
return undefined;
}
if (node.type === 'NullLiteral') {
return null;
}
if (node.type === 'ObjectExpression') {
return genProps(node.properties);
}
if (node.type === 'ArrayExpression') {
return node.elements.reduce((acc, el) => [
...acc,
...(el.type === 'SpreadElement'
? exprToObject(el.argument)
: [exprToObject(el)])
], []);
}
}
// converts ObjectExpressions to js object
function genProps(props) {
return props.reduce((acc, prop) => {
if (prop.type === 'SpreadElement') {
return Object.assign(Object.assign({}, acc), exprToObject(prop.argument));
}
else if (prop.type !== 'ObjectMethod') {
const v = exprToObject(prop.value);
if (v !== undefined) {
return Object.assign(Object.assign({}, acc), { [prop.key.name || prop.key.value]: v });
}
}
return acc;
}, {});
}
// read page config from a sfc file instead of the regular config file
function readSFCPageConfig(configPath) {
if (!fs.existsSync(configPath))
return {};
const sfcSource = fs.readFileSync(configPath, 'utf8');
const dpcReg = /definePageConfig\(\{[\w\W]+?\}\)/g;
const matches = sfcSource.match(dpcReg);
let result = {};
if (matches && matches.length === 1) {
const callExprHandler = (p) => {
const { callee } = p.node;
if (!callee.name)
return;
if (callee.name && callee.name !== 'definePageConfig')
return;
const configNode = p.node.arguments[0];
result = exprToObject(configNode);
p.stop();
};
const configSource = matches[0];
const babel = require('@babel/core');
const ast = babel.parse(configSource, { filename: '' });
babel.traverse(ast.program, { CallExpression: callExprHandler });
}
return result;
}
function readPageConfig(configPath) {
let result = {};
const extNames = ['.js', '.jsx', '.ts', '.tsx', '.vue'];
// check source file extension
extNames.some(ext => {
const tempPath = configPath.replace('.config', ext);
if (fs.existsSync(tempPath)) {
try {
result = readSFCPageConfig(tempPath);
}
catch (error) {
result = {};
}
return true;
}
});
return result;
}
exports.readPageConfig = readPageConfig;
function readConfig(configPath) {
let result = {};
if (fs.existsSync(configPath)) {
const importPaths = constants_1.REG_SCRIPTS.test(configPath) ? analyzeImport(configPath) : [];
(0, swcRegister_1.default)({
only: [
configPath,
filepath => importPaths.includes(filepath)
],
plugin: m => new swcRegister_1.InjectDefineConfigHeader().visitProgram(m)
});
importPaths.concat([configPath]).forEach(item => {
delete require.cache[item];
});
result = (0, exports.getModuleDefaultExport)(require(configPath));
}
else {
result = readPageConfig(configPath);
}
return result;
}
exports.readConfig = readConfig;
//# sourceMappingURL=utils.js.map