All files cli-runner.ts

100% Statements 13/13
100% Branches 12/12
100% Functions 1/1
100% Lines 13/13

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        1x                                                 9x 9x   9x 9x                           9x 2x 2x     5x                   5x 9x   3x 3x      
import { parseArgs } from "node:util";
 
import { mangle } from "./index";
 
const help = `Usage: terser-mangle [options] [files, directories, or globs...]
 
Deterministically mangle properties ending in a single underscore.
 
Options:
  -c, --cache <file>     Cache file (default: mangle-cache.json)
  -d, --out-dir <dir>    Write files beneath a directory
  -o, --out-file <file>  Write one input to a file
      --reserve <name>   Preserve a property name (repeatable)
      --minify           Also compress and mangle identifiers
  -h, --help             Show this help
 
With no inputs, terser-mangle recursively processes dist.
Inputs are changed in place unless an output option is provided.`;
 
export interface CliEnvironment {
  cwd?: string;
  stderr?: (message: string) => void;
  stdout?: (message: string) => void;
}
 
export async function runCli(
  args: readonly string[] = process.argv.slice(2),
  environment: CliEnvironment = {},
): Promise<number> {
  const stdout = environment.stdout ?? console.log;
  const stderr = environment.stderr ?? console.error;
 
  try {
    const { positionals, values } = parseArgs({
      allowPositionals: true,
      args: [...args],
      options: {
        cache: { short: "c", type: "string" },
        help: { short: "h", type: "boolean" },
        minify: { type: "boolean" },
        "out-dir": { short: "d", type: "string" },
        "out-file": { short: "o", type: "string" },
        reserve: { multiple: true, type: "string" },
      },
      strict: true,
    });
 
    if (values.help) {
      stdout(help);
      return 0;
    }
 
    const result = await mangle({
      cache: values.cache,
      cwd: environment.cwd,
      inputs: positionals,
      minify: values.minify,
      outDir: values["out-dir"],
      outFile: values["out-file"],
      reserved: values.reserve,
    });
 
    stdout(`Mangled ${result.files.length} file${result.files.length === 1 ? "" : "s"}.`);
    return 0;
  } catch (error) {
    stderr(`terser-mangle: ${error instanceof Error ? error.message : String(error)}`);
    return 1;
  }
}