CLIUtils.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import * as fs from 'fs';
  2. import * as mkdirp from 'mkdirp';
  3. import * as path from 'path';
  4. import { TObject } from '../../types/TObject';
  5. import { JavaScriptObfuscatorCLI } from '../JavaScriptObfuscatorCLI';
  6. export class CLIUtils {
  7. /**
  8. * @param {string} inputPath
  9. * @returns {string}
  10. */
  11. public static getOutputCodePath (inputPath: string): string {
  12. return inputPath
  13. .split('.')
  14. .map((value: string, index: number) => {
  15. return index === 0 ? `${value}${JavaScriptObfuscatorCLI.obfuscatedFilePrefix}` : value;
  16. })
  17. .join('.');
  18. }
  19. /**
  20. * @param {string} outputCodePath
  21. * @param {string} sourceMapFileName
  22. * @returns {string}
  23. */
  24. public static getOutputSourceMapPath (outputCodePath: string, sourceMapFileName: string = ''): string {
  25. if (sourceMapFileName) {
  26. outputCodePath = `${outputCodePath.substring(
  27. 0, outputCodePath.lastIndexOf('/')
  28. )}/${sourceMapFileName}`;
  29. }
  30. if (!/\.js\.map$/.test(outputCodePath)) {
  31. outputCodePath = `${outputCodePath.split('.')[0]}.js.map`;
  32. } else if (/\.js$/.test(outputCodePath)) {
  33. outputCodePath += '.map';
  34. }
  35. return outputCodePath;
  36. }
  37. /**
  38. * @param {string} configPath
  39. * @returns {TObject}
  40. */
  41. public static getUserConfig (configPath: string): TObject {
  42. let config: Object;
  43. try {
  44. config = require(configPath);
  45. } catch (e) {
  46. try {
  47. config = __non_webpack_require__(configPath);
  48. } catch (e) {
  49. throw new ReferenceError('Given config path must be a valid file path');
  50. }
  51. }
  52. return config;
  53. }
  54. /**
  55. * @param {string} outputPath
  56. * @param {string} data
  57. */
  58. public static writeFile (outputPath: string, data: string): void {
  59. mkdirp.sync(path.dirname(outputPath));
  60. fs.writeFileSync(outputPath, data, {
  61. encoding: JavaScriptObfuscatorCLI.encoding
  62. });
  63. }
  64. }