All files / src/command baseSubCommand.js

100% Statements 80/80
100% Branches 32/32
100% Functions 22/22
100% Lines 77/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248    23x                   23x                                                                 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 825x                     14x             78x   78x 11x   78x   3x 1x       1x 1x 1x 1x                 79x   119x 119x 119x                   5x   5x 5x                   51x 51x 306x 306x 169x     51x                   298x 3x   295x 2x   293x                       119x 119x 300x 5x   295x   119x                         50x 50x 76x 75x 75x       50x 50x 50x 10x   50x   50x 50x         50x 150x   50x 50x       50x 50x 50x   1x   50x 50x   13x           37x 37x 1x 1x         37x                     2x          
import { interopImportCJSDefault } from 'node-cjs-interop';
import asyncValidator from 'async-validator';
const Schema = interopImportCJSDefault(asyncValidator);
 
import inquirer from 'inquirer';
import ora from 'ora';
import { logger } from '../utils/myLogger.js';
import { camelCase } from '../utils/utils.js';
import { commonGlobalOptionValidatorDesc, globalOptionsPrompts, strictGlobalOptionValidatorDesc } from '../utils/constants.js';
 
// Schema.warning = () => {}; // TypeError: Cannot add property warning, object is not extensible
 
const defaultOraOptions = {
  text: 'AElf loading...'
};
/**
 * @typedef {import('commander').Command} Command
 * @typedef {import('ora').Options} OraOptions
 * @typedef {import('../../types/rc/index.js').default} Registry
 */
 
/**
 * @class
 */
class BaseSubCommand {
  /**
   * @param {string} commandName sub command name
   * @param {{ [key: string]: any }[]} parameters sub command parameters
   * @param {string} description sub command description
   * @param {{ [key: string]: any }[]} options sub command options
   * @param {string[]} usage make examples
   * @param {Registry} rc instance of Registry
   * @param {{ [key: string]: any }} validatorDesc rules of async-validator
   * @param {{ [key: string]: any }} oraOptions an ora options
   */
  constructor(
    commandName,
    parameters = [],
    description,
    options = [],
    usage = [],
    rc,
    validatorDesc = strictGlobalOptionValidatorDesc,
    oraOptions = defaultOraOptions
  ) {
    this.commandName = commandName;
    this.parameters = parameters;
    this.description = description;
    this.options = options;
    this.validatorDesc = {};
    this.usage = usage;
    this.rc = rc;
    this.oraInstance = ora(oraOptions);
    this.customPrompts = false;
    Object.entries(validatorDesc).forEach(([key, value]) => {
      this.validatorDesc[key] = {
        ...strictGlobalOptionValidatorDesc[key],
        ...value
      };
    });
  }
  /**
   * Sets custom prompts.
   * @param {any} val - The value to set for custom prompts.
   */
  setCustomPrompts(val) {
    this.customPrompts = val;
  }
  /**
   * Initializes the sub command with commander.
   * @param {Command} commander - The commander instance.
   */
  init(commander) {
    let command = commander.command(`${this.commandName} ${this.getParameters()}`).description(this.description);
 
    for (const { flag, description } of this.options) {
      command = command.option(flag, description);
    }
    command
      .action(async (...args) => {
        await this.run(commander, ...args);
        this.oraInstance.stop();
      })
      .on('--help', () => {
        // todo: chalk
        console.info('');
        console.info('Examples:');
        console.info('');
        console.info(`${this.makeExamples().join('\n')}`);
      });
  }
 
  /**
   * Retrieves parameters as a string.
   * @returns {string} Parameters string.
   */
  getParameters() {
    return this.parameters
      .map(v => {
        const { name, required = false, extraName = [] } = v;
        const symbol = [name, ...extraName].join('|');
        return required ? `<${symbol}>` : `[${symbol}]`;
      })
      .join(' ');
  }
 
  /**
   * Handles errors related to universal options.
   * @param {any} error - The error to handle.
   */
  handleUniOptionsError(error) {
    const { errors = [] } = error;
    // @ts-ignore
    logger.error(errors.reduce((acc, i) => `${acc}${i.message}\n`, ''));
    process.exit(1);
  }
 
  /**
   * Retrieves universal configuration.
   * @static
   * @param {Command} commander - The commander instance.
   * @returns {Record<string, any>} Universal configuration.
   */
  static getUniConfig(commander) {
    const result = {};
    Object.keys(commonGlobalOptionValidatorDesc).forEach(v => {
      const options = commander.opts();
      if (options[v]) {
        result[v] = options[v];
      }
    });
    return result;
  }
 
  /**
   * Parses a boolean value.
   * @static
   * @param {any} val - The value to parse.
   * @returns {any} Parsed boolean value.
   */
  static parseBoolean(val) {
    if (val === 'true') {
      return true;
    }
    if (val === 'false') {
      return false;
    }
    return val;
  }
 
  /**
   * Normalizes configuration object.
   * @static
   * @param {any} obj - The configuration object to normalize.
   * @returns {Record<string, any>} Normalized configuration object.
   */
  static normalizeConfig(obj) {
    // dash to camel-case
    // 'true', 'false' to true, false
    const result = {};
    Object.entries(obj).forEach(([key, value]) => {
      if (value === '' || value === null || value === undefined) {
        return;
      }
      result[camelCase(key)] = BaseSubCommand.parseBoolean(value);
    });
    return result;
  }
  /**
   * Runs the sub command.
   * @param {Command} commander - The commander instance.
   * @param {...any} args - Additional arguments.
   * @returns {Promise<{
   *   localOptions: { [key: string]: any },
   *   options: { [key: string]: any },
   *   subOptions: { [key: string]: any }
   * } | void>} Promise resolving to options or void.
   */
  async run(commander, ...args) {
    let subCommandOptions = {};
    args.slice(0, this.parameters.length).forEach((v, i) => {
      if (v !== undefined) {
        const { name, filter = val => val } = this.parameters[i];
        subCommandOptions[name] = filter(v);
      }
    });
    // sub command options
    const lastArg = args.slice(this.parameters.length)[0];
    const localOptions = {};
    this.options.forEach(({ name }) => {
      localOptions[name] = lastArg?.[name] || undefined;
    });
    const uniOptions = BaseSubCommand.getUniConfig(commander);
    // get options from global config and process.argv
    const rc = await this.rc.getConfigs();
    let options = BaseSubCommand.normalizeConfig({
      ...rc,
      ...uniOptions
    });
 
    const globalPrompts = globalOptionsPrompts.filter(
      prompt => this.validatorDesc[prompt.name]?.required && !options[prompt.name]
    );
    const globalPromptsAns = await inquirer.prompt(globalPrompts);
    options = {
      ...options,
      ...globalPromptsAns
    };
    this.validator = new Schema(this.validatorDesc);
    try {
      await this.validator.validate(options);
    } catch (e) {
      this.handleUniOptionsError(e);
    }
    subCommandOptions = BaseSubCommand.normalizeConfig(subCommandOptions);
    if (this.customPrompts) {
      // custom prompts process
      return {
        localOptions,
        options,
        subOptions: subCommandOptions
      };
    }
    const subOptionsLength = Object.keys(subCommandOptions).length;
    if (subOptionsLength < this.parameters.length) {
      const response = BaseSubCommand.normalizeConfig(await inquirer.prompt(this.parameters.slice(subOptionsLength)));
      subCommandOptions = {
        ...subCommandOptions,
        ...response
      };
    }
    return {
      localOptions,
      options,
      subOptions: subCommandOptions
    };
  }
  /**
   * Generates examples for usage.
   * @returns {string[]} Array of example strings.
   */
  makeExamples() {
    return this.usage.map(cmd => `aelf-command ${this.commandName} ${cmd}`);
  }
}
 
export default BaseSubCommand;