@pecometer/peco-cli
Version:
Pecometer Command Line Interface Application with monorepo support
5 lines • 6.08 kB
JavaScript
"use strict";
/**
* @author Sean Hutchinson
* @copyright Pecometer Software Ltd
*/Object.defineProperty(exports,"__esModule",{value:!0}),exports.CCommandLineApp=void 0;const _=require("lodash"),moment=require("moment"),path=require("node:path"),tsconfig_paths_1=require("tsconfig-paths"),base_command_1=require("./base-command"),file_1=require("./file"),check_reg_version_1=require("../helpers/check-reg-version"),check_update_1=require("../commands/check-update"),create_app_1=require("../commands/create-app"),dotenv_1=require("dotenv"),generate_env_1=require("../commands/generate-env"),package_json_1=require("../package.json"),ts_node_1=require("ts-node"),version_1=require("../commands/version");class CCommandLineApp{constructor(){this._output=new base_command_1.CBaseCommand,this._fileHelper=new file_1.CFileHelper,this._isTypescript=!1,this._cwd=process.cwd(),this._commandsMap={"check-update":check_update_1.CheckUpdate,"create-app":create_app_1.CreateApp,"generate-env":generate_env_1.GenerateEnv,version:version_1.Version},process.on("unhandledRejection",reason=>{console.error(reason),process.exit()})}async run(){this._output.notice(`PecoTS CLI, © ${moment().year()} Pecometer Software Limited, All rights reserved.`);try{const paramData=await this._parseArguments(process.argv);if(!0===paramData){process.__pecoCli=!0;const backendDir=path.dirname(this._location),needsDirectoryChange=backendDir!==this._cwd;if(needsDirectoryChange&&process.chdir(backendDir),this._isTypescript){(0,ts_node_1.register)({project:"./tsconfig.json",transpileOnly:!0});const config=(0,tsconfig_paths_1.loadConfig)("./tsconfig.json");(0,tsconfig_paths_1.register)({baseUrl:config.absoluteBaseUrl,paths:config.paths}),process.__pecoCli_isTypeScript=!0}this._output.notice("Executing project command line app."),await Promise.resolve(`${this._location}`).then(s=>require(s)),needsDirectoryChange&&process.chdir(this._cwd)}else{const{cls,method,params}=paramData,command=new this._commandsMap[cls];if(!command[method])throw new Error(`Method \`${method}\` does not exists on class \`${_.capitalize(cls)}\`.`);const result=command[method](...params);if(result)return result.then(async()=>{await this._checkVersion(cls),this._output.outputNewLine()}).catch(err=>{throw this._output.outputNewLine(),err});await this._checkVersion(cls),this._output.outputNewLine()}}catch(err){err instanceof Error?(this._output.error(err.message),this._output.error(err.stack)):this._output.error(err),this._output.outputNewLine()}}async _parseArguments(args){let index=_.findIndex(args,o=>o.includes("node"));if(-1===index||index+1>=args.length)throw new Error("Unable to process request. Unknown Error during command parse.");if(index+=2,index>=args.length){if(await this._checkHasBackendApplication())return!0;this._output.outputNewLine(),this._output.warn("No command selected, use a command below to execute the action:");for(const key in this._commandsMap)if(this._commandsMap[key]){const command=new this._commandsMap[key];this._output.warn(` -- ${key} - ${command.description}`)}throw this._output.outputNewLine(),this._output.info("Tip: For monorepo structures, set PECOTS_BACKEND_PATH in environment or .env file to specify backend location."),this._output.outputNewLine(),new Error("No command was passed to PecoCLI.")}const[cls]=args[index].split("."),method=args[index].split(".")[1]||"execute";if(void 0===this._commandsMap[cls]){if(await this._checkHasBackendApplication())return!0;throw new Error(`Unknown command call \`${cls}\``)}return{cls,method,params:_.slice(args,index+1)}}_getEnvironmentBackendPath(){try{(0,dotenv_1.config)({path:path.join(this._cwd,".env")})}catch(_a){}const envPath=process.env.PECOTS_BACKEND_PATH;return null==envPath||"string"==typeof envPath&&""===envPath.trim()?null:envPath.trim()}_resolveBackendPath(envPath){return path.isAbsolute(envPath)?envPath:path.resolve(this._cwd,envPath)}async _checkBackendAtPath(basePath){const tsPath=path.join(basePath,"index.ts");if(await this._fileHelper.exists(tsPath))return{isTypescript:!0,location:tsPath};const jsPath=path.join(basePath,"index.js");return await this._fileHelper.exists(jsPath)?{isTypescript:!1,location:jsPath}:null}async _checkHasBackendApplication(){const envPath=this._getEnvironmentBackendPath();if(envPath){const resolvedPath=this._resolveBackendPath(envPath);this._output.info(`Checking environment variable path: ${resolvedPath}`,!1);const envResult=await this._checkBackendAtPath(resolvedPath);if(envResult)return this._location=envResult.location,this._isTypescript=envResult.isTypescript,this._output.info(`Backend found via environment variable at: ${envResult.location}`,!1),!0;this._output.warn(`Invalid environment variable path: ${resolvedPath}`,!1)}if(this._output.info(`Checking current directory: ${this._cwd}`,!1),await this._fileHelper.exists(path.join(this._cwd,"index.ts")))return this._location=path.join(this._cwd,"index.ts"),this._isTypescript=!0,!0;const backendDir=path.join(this._cwd,"backend");return this._output.info(`Checking backend subdirectory: ${backendDir}`,!1),await this._fileHelper.exists(path.join(this._cwd,"backend","index.ts"))?(this._location=path.join(this._cwd,"backend","index.ts"),this._isTypescript=!0,!0):(this._output.info(`Checking current directory for JavaScript: ${this._cwd}`,!1),await this._fileHelper.exists(path.join(this._cwd,"index.js"))?(this._location=path.join(this._cwd,"index.js"),!0):(this._output.info(`Checking backend subdirectory for JavaScript: ${backendDir}`,!1),!!await this._fileHelper.exists(path.join(this._cwd,"backend","index.js"))&&(this._location=path.join(this._cwd,"backend","index.js"),!0)))}async _checkVersion(cls=""){if("check-update"===cls)return;const result=await(0,check_reg_version_1.CheckRegistryVersion)();!0!==result&&(this._output.outputNewLine(),this._output.info("There is an update ready to be installed.",!0),this._output.info(`${package_json_1.name} => ${result}`,!0),this._output.info(`Run npm i -g ${package_json_1.name}`,!0),this._output.outputNewLine())}}exports.CCommandLineApp=CCommandLineApp;