All files global.js

87.14% Statements 61/70
74.28% Branches 26/35
100% Functions 11/11
86.56% Lines 58/67

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 2027x 7x 7x 7x 7x                     7x             7x               7x 6x 7x 1x     6x 4x     2x 4x 2x     6x 1x     5x 2x 4x 2x     3x 3x                       7x               7x   1x 1x 1x                 1x               7x 7x 7x                                           7x       7x 7x 7x   7x       7x 1x         7x 7x 7x         7x                     7x 1x   1x 1x         1x               7x     1x 2x 1x 1x     1x   1x 1x       7x                      
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { consoleMessage } = require('./logger');
 
/**
 * @module Global
 */
 
/**
 * JS file extensions
 *
 * @type {string[]}
 */
const jsFileExtensions = ['js', 'jsx', 'mjs', 'cjs'];
 
/**
 * TS file extensions
 *
 * @type {string[]}
 */
const tsFileExtensions = ['ts', 'tsx', 'mts', 'cts'];
 
/**
 * Handle a variety of error types consistently.
 *
 * @param {string|Array|object|any} errors
 * @returns {string|any|any[]}
 */
const errorMessageHandler = errors => {
  const parseErrorObject = err => {
    if (typeof err === 'string') {
      return err;
    }
 
    if (err.message) {
      return err.message;
    }
 
    const updatedEntries = [];
    Object.entries(err).forEach(([key, value]) => updatedEntries.push(`${key}: ${value}`));
    return updatedEntries.join('\n');
  };
 
  if (typeof errors === 'string') {
    return errors;
  }
 
  if (Array.isArray(errors)) {
    const updatedErrors = [];
    errors.forEach(err => updatedErrors.push(parseErrorObject(err)));
    return updatedErrors;
  }
 
  Eif (typeof errors === 'object') {
    return parseErrorObject(errors);
  }
 
  return errors;
};
 
/**
 * Check if "is a Promise", "Promise like".
 *
 * @param {Promise|*} obj
 * @returns {boolean}
 */
const isPromise = obj => /^\[object (Promise|Async|AsyncFunction)]/.test(Object.prototype.toString.call(obj));
 
/**
 * Import module regardless of CommonJS or ES.
 *
 * @param {string} file
 * @returns {Promise<any>}
 */
const dynamicImport = async file => {
  let result;
  try {
    if (process.env._WELDABLE_TEST === 'true') {
      result = require(file);
    } else E{
      // eslint-disable-next-line node/no-unsupported-features/es-syntax
      result = await import(file);
    }
  } catch (e) {
    consoleMessage.warn(`Dynamic import for ${file}: ${e.message}`);
  }
 
  return result;
};
 
/**
 * Global context path. On load set path.
 *
 * @type {string}
 */
const contextPath = (() => {
  Eif (process.env._WELDABLE_TEST === 'true') {
    return path.join('..', '__fixtures__');
  }
 
  if (process.env._WELDABLE_DEV === 'true') {
    return path.join(__dirname, '..', './__fixtures__');
  }
 
  return process.cwd();
})();
 
/**
 * Create a file with a fallback name based on hashed contents.
 *
 * @param {string} contents
 * @param {object} options
 * @param {string} options.dir
 * @param {string} options.ext
 * @param {string} options.encoding
 * @param {string} options.filename
 * @param {boolean} options.resetDir
 * @returns {{path: string, file: (*|string), contents: string, dir: string}}
 */
const createFile = (
  contents,
  { dir = path.resolve(contextPath), ext = 'txt', encoding = 'utf8', filename, resetDir = false } = {}
) => {
  const updatedFileName = filename || crypto.createHash('md5').update(contents).digest('hex');
  const file = path.extname(updatedFileName) ? updatedFileName : `${updatedFileName}.${ext}`;
  const filePath = path.join(dir, file);
 
  Iif (resetDir && fs.existsSync(dir)) {
    fs.rmSync(dir, { recursive: true });
  }
 
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
 
  let updatedContents;
 
  try {
    fs.writeFileSync(filePath, contents, { encoding });
    updatedContents = fs.readFileSync(filePath, { encoding });
  } catch (e) {
    consoleMessage.error(e.message);
  }
 
  return { dir, file, path: filePath, contents: updatedContents };
};
 
/**
 * Execute a command
 *
 * @param {string} cmd
 * @param {object} settings
 * @param {string} settings.errorMessage
 * @returns {string}
 */
const runCmd = (cmd, { errorMessage = 'Skipping... {0}' } = {}) => {
  let stdout = '';
 
  try {
    stdout = execSync(cmd);
  } catch (e) {
    consoleMessage.error(errorMessage.replace('{0}', e.message));
  }
 
  return stdout.toString();
};
 
/**
 * Global options/settings. One time _set, then freeze.
 *
 * @type {{contextPath: string, _set: *}}
 */
const OPTIONS = {
  contextPath,
  set _set(obj) {
    Object.entries(obj).forEach(([key, value]) => {
      if (typeof value === 'function') {
        this[key] = value.call(this);
        return;
      }
 
      this[key] = value;
    });
    delete this._set;
    Object.freeze(this);
  }
};
 
module.exports = {
  contextPath,
  createFile,
  dynamicImport,
  errorMessageHandler,
  jsFileExtensions,
  isPromise,
  OPTIONS,
  runCmd,
  tsFileExtensions
};