code:
/***********************************************************************

  A JavaScript tokenizer / parser / beautifier / compressor.
  https://github.com/mishoo/UglifyJS2

  -------------------------------- (C) ---------------------------------

                           Author: Mihai Bazon
                         <mihai.bazon@gmail.com>
                       http://mihai.bazon.net/blog

  Distributed under the BSD license:

    Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

        * Redistributions of source code must retain the above
          copyright notice, this list of conditions and the following
          disclaimer.

        * Redistributions in binary form must reproduce the above
          copyright notice, this list of conditions and the following
          disclaimer in the documentation and/or other materials
          provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.

 ***********************************************************************/

"use strict";

import {
    defaults,
    keep_name,
    mergeSort,
    push_uniq,
    make_node,
    return_false,
    return_this,
    return_true,
    string_template,
} from "./utils/index.js";
import {
    AST_Arrow,
    AST_Block,
    AST_Call,
    AST_Class,
    AST_Conditional,
    AST_DefClass,
    AST_Defun,
    AST_Destructuring,
    AST_Dot,
    AST_DotHash,
    AST_Export,
    AST_For,
    AST_ForIn,
    AST_ForOf,
    AST_Function,
    AST_Import,
    AST_IterationStatement,
    AST_Label,
    AST_LabeledStatement,
    AST_LabelRef,
    AST_Lambda,
    AST_LoopControl,
    AST_NameMapping,
    AST_Node,
    AST_Scope,
    AST_Sequence,
    AST_String,
    AST_Sub,
    AST_Switch,
    AST_SwitchBranch,
    AST_Symbol,
    AST_SymbolBlockDeclaration,
    AST_SymbolCatch,
    AST_SymbolClass,
    AST_SymbolConst,
    AST_SymbolDefClass,
    AST_SymbolDefun,
    AST_SymbolExport,
    AST_SymbolFunarg,
    AST_SymbolImport,
    AST_SymbolLambda,
    AST_SymbolLet,
    AST_SymbolMethod,
    AST_SymbolRef,
    AST_SymbolVar,
    AST_Toplevel,
    AST_VarDef,
    AST_With,
    TreeWalker,
    walk,
    walk_abort
} from "./ast.js";
import {
    ALL_RESERVED_WORDS,
    js_error,
} from "./parse.js";

const MASK_EXPORT_DONT_MANGLE = 1 << 0;
const MASK_EXPORT_WANT_MANGLE = 1 << 1;

let function_defs = null;
let unmangleable_names = null;
/**
 * When defined, there is a function declaration somewhere that's inside of a block.
 * See https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics
*/
let scopes_with_block_defuns = null;

class SymbolDef {
    constructor(scope, orig, init) {
        this.name = orig.name;
        this.orig = [ orig ];
        this.init = init;
        this.eliminated = 0;
        this.assignments = 0;
        this.scope = scope;
        this.replaced = 0;
        this.global = false;
        this.export = 0;
        this.mangled_name = null;
        this.undeclared = false;
        this.id = SymbolDef.next_id++;
        this.chained = false;
        this.direct_access = false;
        this.escaped = 0;
        this.recursive_refs = 0;
        this.references = [];
        this.should_replace = undefined;
        this.single_use = false;
        this.fixed = false;
        Object.seal(this);
    }
    fixed_value() {
        if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed;
        return this.fixed();
    }
    unmangleable(options) {
        if (!options) options = {};

        if (
            function_defs &&
            function_defs.has(this.id) &&
            keep_name(options.keep_fnames, this.orig[0].name)
        ) return true;

        return this.global && !options.toplevel
            || (this.export & MASK_EXPORT_DONT_MANGLE)
            || this.undeclared
            || !options.eval && this.scope.pinned()
            || (this.orig[0] instanceof AST_SymbolLambda
                  || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name)
            || this.orig[0] instanceof AST_SymbolMethod
            || (this.orig[0] instanceof AST_SymbolClass
                  || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
    }
    mangle(options) {
        const cache = options.cache && options.cache.props;
        if (this.global && cache && cache.has(this.name)) {
            this.mangled_name = cache.get(this.name);
        } else if (!this.mangled_name && !this.unmangleable(options)) {
            var s = this.scope;
            var sym = this.orig[0];
            if (options.ie8 && sym instanceof AST_SymbolLambda)
                s = s.parent_scope;
            const redefinition = redefined_catch_def(this);
            this.mangled_name = redefinition
                ? redefinition.mangled_name || redefinition.name
                : s.next_mangled(options, this);
            if (this.global && cache) {
                cache.set(this.name, this.mangled_name);
            }
        }
    }
}

SymbolDef.next_id = 1;

function redefined_catch_def(def) {
    if (def.orig[0] instanceof AST_SymbolCatch
        && def.scope.is_block_scope()
    ) {
        return def.scope.get_defun_scope().variables.get(def.name);
    }
}

AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
    options = defaults(options, {
        cache: null,
        ie8: false,
        safari10: false,
        module: false,
    });

    if (!(toplevel instanceof AST_Toplevel)) {
        throw new Error("Invalid toplevel scope");
    }

    // pass 1: setup scope chaining and handle definitions
    var scope = this.parent_scope = parent_scope;
    var labels = new Map();
    var defun = null;
    var in_destructuring = null;
    var for_scopes = [];
    var tw = new TreeWalker((node, descend) => {
        if (node.is_block_scope()) {
            const save_scope = scope;
            node.block_scope = scope = new AST_Scope(node);
            scope._block_scope = true;
            scope.init_scope_vars(save_scope);
            scope.uses_with = save_scope.uses_with;
            scope.uses_eval = save_scope.uses_eval;

            if (options.safari10) {
                if (node instanceof AST_For || node instanceof AST_ForIn || node instanceof AST_ForOf) {
                    for_scopes.push(scope);
                }
            }

            if (node instanceof AST_Switch) {
                // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
                // AST_Switch has a scope within the body, but it itself "is a block scope"
                // This means the switched expression has to belong to the outer scope
                // while the body inside belongs to the switch itself.
                // This is pretty nasty and warrants an AST change
                const the_block_scope = scope;
                scope = save_scope;
                node.expression.walk(tw);
                scope = the_block_scope;
                for (let i = 0; i < node.body.length; i++) {
                    node.body[i].walk(tw);
                }
            } else {
                descend();
            }
            scope = save_scope;
            return true;
        }
        if (node instanceof AST_Destructuring) {
            const save_destructuring = in_destructuring;
            in_destructuring = node;
            descend();
            in_destructuring = save_destructuring;
            return true;
        }
        if (node instanceof AST_Scope) {
            node.init_scope_vars(scope);
            var save_scope = scope;
            var save_defun = defun;
            var save_labels = labels;
            defun = scope = node;
            labels = new Map();
            descend();
            scope = save_scope;
            defun = save_defun;
            labels = save_labels;
            return true;        // don't descend again in TreeWalker
        }
        if (node instanceof AST_LabeledStatement) {
            var l = node.label;
            if (labels.has(l.name)) {
                throw new Error(string_template("Label {name} defined twice", l));
            }
            labels.set(l.name, l);
            descend();
            labels.delete(l.name);
            return true;        // no descend again
        }
        if (node instanceof AST_With) {
            for (var s = scope; s; s = s.parent_scope)
                s.uses_with = true;
            return;
        }
        if (node instanceof AST_Symbol) {
            node.scope = scope;
        }
        if (node instanceof AST_Label) {
            node.thedef = node;
            node.references = [];
        }
        if (node instanceof AST_SymbolLambda) {
            defun.def_function(node, node.name == "arguments" ? undefined : defun);
        } else if (node instanceof AST_SymbolDefun) {
            // Careful here, the scope where this should be defined is
            // the parent scope.  The reason is that we enter a new
            // scope when we encounter the AST_Defun node (which is
            // instanceof AST_Scope) but we get to the symbol a bit
            // later.
            const closest_scope = defun.parent_scope;

            // In strict mode, function definitions are block-scoped
            node.scope = tw.directives["use strict"]
                ? closest_scope
                : closest_scope.get_defun_scope();

            mark_export(node.scope.def_function(node, defun), 1);
        } else if (node instanceof AST_SymbolClass) {
            mark_export(defun.def_variable(node, defun), 1);
        } else if (node instanceof AST_SymbolImport) {
            scope.def_variable(node);
        } else if (node instanceof AST_SymbolDefClass) {
            // This deals with the name of the class being available
            // inside the class.
            mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
        } else if (
            node instanceof AST_SymbolVar
            || node instanceof AST_SymbolLet
            || node instanceof AST_SymbolConst
            || node instanceof AST_SymbolCatch
        ) {
            var def;
            if (node instanceof AST_SymbolBlockDeclaration) {
                def = scope.def_variable(node, null);
            } else {
                def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
            }
            if (!def.orig.every((sym) => {
                if (sym === node) return true;
                if (node instanceof AST_SymbolBlockDeclaration) {
                    return sym instanceof AST_SymbolLambda;
                }
                return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst);
            })) {
                js_error(
                    `"${node.name}" is redeclared`,
                    node.start.file,
                    node.start.line,
                    node.start.col,
                    node.start.pos
                );
            }
            if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2);
            if (defun !== scope) {
                node.mark_enclosed();
                var def = scope.find_variable(node);
                if (node.thedef !== def) {
                    node.thedef = def;
                    node.reference();
                }
            }
        } else if (node instanceof AST_LabelRef) {
            var sym = labels.get(node.name);
            if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
                name: node.name,
                line: node.start.line,
                col: node.start.col
            }));
            node.thedef = sym;
        }
        if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) {
            js_error(
                `"${node.TYPE}" statement may only appear at the top level`,
                node.start.file,
                node.start.line,
                node.start.col,
                node.start.pos
            );
        }
    });

    if (options.module) {
        tw.directives["use strict"] = true;
    }

    this.walk(tw);

    function mark_export(def, level) {
        if (in_destructuring) {
            var i = 0;
            do {
                level++;
            } while (tw.parent(i++) !== in_destructuring);
        }
        var node = tw.parent(level);
        if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) {
            var exported = node.exported_definition;
            if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) {
                def.export = MASK_EXPORT_WANT_MANGLE;
            }
        }
    }

    // pass 2: find back references and eval
    const is_toplevel = this instanceof AST_Toplevel;
    if (is_toplevel) {
        this.globals = new Map();
    }

    var tw = new TreeWalker(node => {
        if (node instanceof AST_LoopControl && node.label) {
            node.label.thedef.references.push(node);
            return true;
        }
        if (node instanceof AST_SymbolRef) {
            var name = node.name;
            if (name == "eval" && tw.parent() instanceof AST_Call) {
                for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
                    s.uses_eval = true;
                }
            }
            var sym;
            if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name
                || !(sym = node.scope.find_variable(name))) {

                sym = toplevel.def_global(node);
                if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE;
            } else if (sym.scope instanceof AST_Lambda && name == "arguments") {
                sym.scope.get_defun_scope().uses_arguments = true;
            }
            node.thedef = sym;
            node.reference();
            if (node.scope.is_block_scope()
                && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) {
                node.scope = node.scope.get_defun_scope();
            }
            return true;
        }
        // ensure mangling works if catch reuses a scope variable
        var def;
        if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) {
            var s = node.scope;
            while (s) {
                push_uniq(s.enclosed, def);
                if (s === def.scope) break;
                s = s.parent_scope;
            }
        }
    });
    this.walk(tw);

    // pass 3: work around IE8 and Safari catch scope bugs
    if (options.ie8 || options.safari10) {
        walk(this, node => {
            if (node instanceof AST_SymbolCatch) {
                var name = node.name;
                var refs = node.thedef.references;
                var scope = node.scope.get_defun_scope();
                var def = scope.find_variable(name)
                    || toplevel.globals.get(name)
                    || scope.def_variable(node);
                refs.forEach(function(ref) {
                    ref.thedef = def;
                    ref.reference();
                });
                node.thedef = def;
                node.reference();
                return true;
            }
        });
    }

    // pass 4: add symbol definitions to loop scopes
    // Safari/Webkit bug workaround - loop init let variable shadowing argument.
    // https://github.com/mishoo/UglifyJS2/issues/1753
    // https://bugs.webkit.org/show_bug.cgi?id=171041
    if (options.safari10) {
        for (const scope of for_scopes) {
            scope.parent_scope.variables.forEach(function(def) {
                push_uniq(scope.enclosed, def);
            });
        }
    }
});

AST_Toplevel.DEFMETHOD("def_global", function(node) {
    var globals = this.globals, name = node.name;
    if (globals.has(name)) {
        return globals.get(name);
    } else {
        var g = new SymbolDef(this, node);
        g.undeclared = true;
        g.global = true;
        globals.set(name, g);
        return g;
    }
});

AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
    this.variables = new Map();         // map name to AST_SymbolVar (variables defined in this scope; includes functions)
    this.uses_with = false;             // will be set to true if this or some nested scope uses the `with` statement
    this.uses_eval = false;             // will be set to true if this or nested scope uses the global `eval`
    this.parent_scope = parent_scope;   // the parent scope
    this.enclosed = [];                 // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
    this.cname = -1;                    // the current index for mangling functions/variables
});

AST_Scope.DEFMETHOD("conflicting_def", function (name) {
    return (
        this.enclosed.find(def => def.name === name)
        || this.variables.has(name)
        || (this.parent_scope && this.parent_scope.conflicting_def(name))
    );
});

AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) {
    return (
        this.enclosed.find(def => def.name === name)
        || this.variables.has(name)
    );
});

AST_Scope.DEFMETHOD("add_child_scope", function (scope) {
    // `scope` is going to be moved into `this` right now.
    // Update the required scopes' information

    if (scope.parent_scope === this) return;

    scope.parent_scope = this;

    // Propagate to this.uses_arguments from arrow functions
    if ((scope instanceof AST_Arrow) && !this.uses_arguments) {
        this.uses_arguments = walk(scope, node => {
            if (
                node instanceof AST_SymbolRef
                && node.scope instanceof AST_Lambda
                && node.name === "arguments"
            ) {
                return walk_abort;
            }

            if (node instanceof AST_Lambda && !(node instanceof AST_Arrow)) {
                return true;
            }
        });
    }

    this.uses_with = this.uses_with || scope.uses_with;
    this.uses_eval = this.uses_eval || scope.uses_eval;

    const scope_ancestry = (() => {
        const ancestry = [];
        let cur = this;
        do {
            ancestry.push(cur);
        } while ((cur = cur.parent_scope));
        ancestry.reverse();
        return ancestry;
    })();

    const new_scope_enclosed_set = new Set(scope.enclosed);
    const to_enclose = [];
    for (const scope_topdown of scope_ancestry) {
        to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e));
        for (const def of scope_topdown.variables.values()) {
            if (new_scope_enclosed_set.has(def)) {
                push_uniq(to_enclose, def);
                push_uniq(scope_topdown.enclosed, def);
            }
        }
    }
});

function find_scopes_visible_from(scopes) {
    const found_scopes = new Set();

    for (const scope of new Set(scopes)) {
        (function bubble_up(scope) {
            if (scope == null || found_scopes.has(scope)) return;

            found_scopes.add(scope);

            bubble_up(scope.parent_scope);
        })(scope);
    }

    return [...found_scopes];
}

// Creates a symbol during compression
AST_Scope.DEFMETHOD("create_symbol", function(SymClass, {
    source,
    tentative_name,
    scope,
    conflict_scopes = [scope],
    init = null
} = {}) {
    let symbol_name;

    conflict_scopes = find_scopes_visible_from(conflict_scopes);

    if (tentative_name) {
        // Implement hygiene (no new names are conflicting with existing names)
        tentative_name =
            symbol_name =
            tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");

        let i = 0;
        while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) {
            symbol_name = tentative_name + "$" + i++;
        }
    }

    if (!symbol_name) {
        throw new Error("No symbol name could be generated in create_symbol()");
    }

    const symbol = make_node(SymClass, source, {
        name: symbol_name,
        scope
    });

    this.def_variable(symbol, init || null);

    symbol.mark_enclosed();

    return symbol;
});

AST_Node.DEFMETHOD("is_block_scope", return_false);
AST_Class.DEFMETHOD("is_block_scope", return_false);
AST_Lambda.DEFMETHOD("is_block_scope", return_false);
AST_Toplevel.DEFMETHOD("is_block_scope", return_false);
AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false);
AST_Block.DEFMETHOD("is_block_scope", return_true);
AST_Scope.DEFMETHOD("is_block_scope", function () {
    return this._block_scope || false;
});
AST_IterationStatement.DEFMETHOD("is_block_scope", return_true);

AST_Lambda.DEFMETHOD("init_scope_vars", function() {
    AST_Scope.prototype.init_scope_vars.apply(this, arguments);
    this.uses_arguments = false;
    this.def_variable(new AST_SymbolFunarg({
        name: "arguments",
        start: this.start,
        end: this.end
    }));
});

AST_Arrow.DEFMETHOD("init_scope_vars", function() {
    AST_Scope.prototype.init_scope_vars.apply(this, arguments);
    this.uses_arguments = false;
});

AST_Symbol.DEFMETHOD("mark_enclosed", function() {
    var def = this.definition();
    var s = this.scope;
    while (s) {
        push_uniq(s.enclosed, def);
        if (s === def.scope) break;
        s = s.parent_scope;
    }
});

AST_Symbol.DEFMETHOD("reference", function() {
    this.definition().references.push(this);
    this.mark_enclosed();
});

AST_Scope.DEFMETHOD("find_variable", function(name) {
    if (name instanceof AST_Symbol) name = name.name;
    return this.variables.get(name)
        || (this.parent_scope && this.parent_scope.find_variable(name));
});

AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
    var def = this.def_variable(symbol, init);
    if (!def.init || def.init instanceof AST_Defun) def.init = init;
    return def;
});

AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
    var def = this.variables.get(symbol.name);
    if (def) {
        def.orig.push(symbol);
        if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) {
            def.init = init;
        }
    } else {
        def = new SymbolDef(this, symbol, init);
        this.variables.set(symbol.name, def);
        def.global = !this.parent_scope;
    }
    return symbol.thedef = def;
});

function next_mangled(scope, options) {
    let defun_scope;
    if (
        scopes_with_block_defuns
        && (defun_scope = scope.get_defun_scope())
        && scopes_with_block_defuns.has(defun_scope)
    ) {
        scope = defun_scope;
    }

    var ext = scope.enclosed;
    var nth_identifier = options.nth_identifier;
    out: while (true) {
        var m = nth_identifier.get(++scope.cname);
        if (ALL_RESERVED_WORDS.has(m)) continue; // skip over "do"

        // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
        // shadow a name reserved from mangling.
        if (options.reserved.has(m)) continue;

        // Functions with short names might collide with base54 output
        // and therefore cause collisions when keep_fnames is true.
        if (unmangleable_names && unmangleable_names.has(m)) continue out;

        // we must ensure that the mangled name does not shadow a name
        // from some parent scope that is referenced in this or in
        // inner scopes.
        for (let i = ext.length; --i >= 0;) {
            const def = ext[i];
            const name = def.mangled_name || (def.unmangleable(options) && def.name);
            if (m == name) continue out;
        }
        return m;
    }
}

AST_Scope.DEFMETHOD("next_mangled", function(options) {
    return next_mangled(this, options);
});

AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
    let name;
    const mangled_names = this.mangled_names;
    do {
        name = next_mangled(this, options);
    } while (mangled_names.has(name));
    return name;
});

AST_Function.DEFMETHOD("next_mangled", function(options, def) {
    // #179, #326
    // in Safari strict mode, something like (function x(x){...}) is a syntax error;
    // a function expression's argument cannot shadow the function expression's name

    var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();

    // the function's mangled_name is null when keep_fnames is true
    var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;

    while (true) {
        var name = next_mangled(this, options);
        if (!tricky_name || tricky_name != name)
            return name;
    }
});

AST_Symbol.DEFMETHOD("unmangleable", function(options) {
    var def = this.definition();
    return !def || def.unmangleable(options);
});

// labels are always mangleable
AST_Label.DEFMETHOD("unmangleable", return_false);

AST_Symbol.DEFMETHOD("unreferenced", function() {
    return !this.definition().references.length && !this.scope.pinned();
});

AST_Symbol.DEFMETHOD("definition", function() {
    return this.thedef;
});

AST_Symbol.DEFMETHOD("global", function() {
    return this.thedef.global;
});

/**
 * Format the mangler options (if any) into their appropriate types
 */
export function format_mangler_options(options) {
    options = defaults(options, {
        eval        : false,
        nth_identifier : base54,
        ie8         : false,
        keep_classnames: false,
        keep_fnames : false,
        module      : false,
        reserved    : [],
        toplevel    : false,
    });
    if (options.module) options.toplevel = true;
    if (!Array.isArray(options.reserved)
        && !(options.reserved instanceof Set)
    ) {
        options.reserved = [];
    }
    options.reserved = new Set(options.reserved);
    // Never mangle arguments
    options.reserved.add("arguments");
    return options;
}

AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
    options = format_mangler_options(options);
    var nth_identifier = options.nth_identifier;

    // We only need to mangle declaration nodes.  Special logic wired
    // into the code generator will display the mangled name if it's
    // present (and for AST_SymbolRef-s it'll use the mangled name of
    // the AST_SymbolDeclaration that it points to).
    var lname = -1;
    var to_mangle = [];

    if (options.keep_fnames) {
        function_defs = new Set();
    }

    const mangled_names = this.mangled_names = new Set();
    unmangleable_names = new Set();

    if (options.cache) {
        this.globals.forEach(collect);
        if (options.cache.props) {
            options.cache.props.forEach(function(mangled_name) {
                mangled_names.add(mangled_name);
            });
        }
    }

    var tw = new TreeWalker(function(node, descend) {
        if (node instanceof AST_LabeledStatement) {
            // lname is incremented when we get to the AST_Label
            var save_nesting = lname;
            descend();
            lname = save_nesting;
            return true;        // don't descend again in TreeWalker
        }
        if (
            node instanceof AST_Defun
            && !(tw.parent() instanceof AST_Scope)
        ) {
            scopes_with_block_defuns = scopes_with_block_defuns || new Set();
            scopes_with_block_defuns.add(node.parent_scope.get_defun_scope());
        }
        if (node instanceof AST_Scope) {
            node.variables.forEach(collect);
            return;
        }
        if (node.is_block_scope()) {
            node.block_scope.variables.forEach(collect);
            return;
        }
        if (
            function_defs
            && node instanceof AST_VarDef
            && node.value instanceof AST_Lambda
            && !node.value.name
            && keep_name(options.keep_fnames, node.name.name)
        ) {
            function_defs.add(node.name.definition().id);
            return;
        }
        if (node instanceof AST_Label) {
            let name;
            do {
                name = nth_identifier.get(++lname);
            } while (ALL_RESERVED_WORDS.has(name));
            node.mangled_name = name;
            return true;
        }
        if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
            to_mangle.push(node.definition());
            return;
        }
    });

    this.walk(tw);

    if (options.keep_fnames || options.keep_classnames) {
        // Collect a set of short names which are unmangleable,
        // for use in avoiding collisions in next_mangled.
        to_mangle.forEach(def => {
            if (def.name.length < 6 && def.unmangleable(options)) {
                unmangleable_names.add(def.name);
            }
        });
    }

    to_mangle.forEach(def => { def.mangle(options); });

    function_defs = null;
    unmangleable_names = null;
    scopes_with_block_defuns = null;

    function collect(symbol) {
        if (symbol.export & MASK_EXPORT_DONT_MANGLE) {
            unmangleable_names.add(symbol.name);
        } else if (!options.reserved.has(symbol.name)) {
            to_mangle.push(symbol);
        }
    }
});

AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
    const cache = options.cache && options.cache.props;
    const avoid = new Set();
    options.reserved.forEach(to_avoid);
    this.globals.forEach(add_def);
    this.walk(new TreeWalker(function(node) {
        if (node instanceof AST_Scope) node.variables.forEach(add_def);
        if (node instanceof AST_SymbolCatch) add_def(node.definition());
    }));
    return avoid;

    function to_avoid(name) {
        avoid.add(name);
    }

    function add_def(def) {
        var name = def.name;
        if (def.global && cache && cache.has(name)) name = cache.get(name);
        else if (!def.unmangleable(options)) return;
        to_avoid(name);
    }
});

AST_Toplevel.DEFMETHOD("expand_names", function(options) {
    options = format_mangler_options(options);
    var nth_identifier = options.nth_identifier;
    if (nth_identifier.reset && nth_identifier.sort) {
        nth_identifier.reset();
        nth_identifier.sort();
    }
    var avoid = this.find_colliding_names(options);
    var cname = 0;
    this.globals.forEach(rename);
    this.walk(new TreeWalker(function(node) {
        if (node instanceof AST_Scope) node.variables.forEach(rename);
        if (node instanceof AST_SymbolCatch) rename(node.definition());
    }));

    function next_name() {
        var name;
        do {
            name = nth_identifier.get(cname++);
        } while (avoid.has(name) || ALL_RESERVED_WORDS.has(name));
        return name;
    }

    function rename(def) {
        if (def.global && options.cache) return;
        if (def.unmangleable(options)) return;
        if (options.reserved.has(def.name)) return;
        const redefinition = redefined_catch_def(def);
        const name = def.name = redefinition ? redefinition.name : next_name();
        def.orig.forEach(function(sym) {
            sym.name = name;
        });
        def.references.forEach(function(sym) {
            sym.name = name;
        });
    }
});

AST_Node.DEFMETHOD("tail_node", return_this);
AST_Sequence.DEFMETHOD("tail_node", function() {
    return this.expressions[this.expressions.length - 1];
});

AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
    options = format_mangler_options(options);
    var nth_identifier = options.nth_identifier;
    if (!nth_identifier.reset || !nth_identifier.consider || !nth_identifier.sort) {
        // If the identifier mangler is invariant, skip computing character frequency.
        return;
    }
    nth_identifier.reset();

    try {
        AST_Node.prototype.print = function(stream, force_parens) {
            this._print(stream, force_parens);
            if (this instanceof AST_Symbol && !this.unmangleable(options)) {
                nth_identifier.consider(this.name, -1);
            } else if (options.properties) {
                if (this instanceof AST_DotHash) {
                    nth_identifier.consider("#" + this.property, -1);
                } else if (this instanceof AST_Dot) {
                    nth_identifier.consider(this.property, -1);
                } else if (this instanceof AST_Sub) {
                    skip_string(this.property);
                }
            }
        };
        nth_identifier.consider(this.print_to_string(), 1);
    } finally {
        AST_Node.prototype.print = AST_Node.prototype._print;
    }
    nth_identifier.sort();

    function skip_string(node) {
        if (node instanceof AST_String) {
            nth_identifier.consider(node.value, -1);
        } else if (node instanceof AST_Conditional) {
            skip_string(node.consequent);
            skip_string(node.alternative);
        } else if (node instanceof AST_Sequence) {
            skip_string(node.tail_node());
        }
    }
});

const base54 = (() => {
    const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
    const digits = "0123456789".split("");
    let chars;
    let frequency;
    function reset() {
        frequency = new Map();
        leading.forEach(function(ch) {
            frequency.set(ch, 0);
        });
        digits.forEach(function(ch) {
            frequency.set(ch, 0);
        });
    }
    function consider(str, delta) {
        for (var i = str.length; --i >= 0;) {
            frequency.set(str[i], frequency.get(str[i]) + delta);
        }
    }
    function compare(a, b) {
        return frequency.get(b) - frequency.get(a);
    }
    function sort() {
        chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
    }
    // Ensure this is in a usable initial state.
    reset();
    sort();
    function base54(num) {
        var ret = "", base = 54;
        num++;
        do {
            num--;
            ret += chars[num % base];
            num = Math.floor(num / base);
            base = 64;
        } while (num > 0);
        return ret;
    }

    return {
        get: base54,
        consider,
        reset,
        sort
    };
})();

export {
    base54,
    SymbolDef,
};


code:
import {
    AST_Accessor,
    AST_Array,
    AST_Arrow,
    AST_Await,
    AST_BigInt,
    AST_Binary,
    AST_Block,
    AST_Break,
    AST_Call,
    AST_Case,
    AST_Class,
    AST_ClassStaticBlock,
    AST_ClassPrivateProperty,
    AST_ClassProperty,
    AST_ConciseMethod,
    AST_Conditional,
    AST_Const,
    AST_Continue,
    AST_Debugger,
    AST_Default,
    AST_Defun,
    AST_Destructuring,
    AST_Directive,
    AST_Do,
    AST_Dot,
    AST_DotHash,
    AST_EmptyStatement,
    AST_Expansion,
    AST_Export,
    AST_False,
    AST_For,
    AST_ForIn,
    AST_Function,
    AST_Hole,
    AST_If,
    AST_Import,
    AST_ImportMeta,
    AST_Infinity,
    AST_LabeledStatement,
    AST_Let,
    AST_NameMapping,
    AST_NaN,
    AST_New,
    AST_NewTarget,
    AST_Node,
    AST_Null,
    AST_Number,
    AST_Object,
    AST_ObjectKeyVal,
    AST_ObjectGetter,
    AST_ObjectSetter,
    AST_PrivateGetter,
    AST_PrivateMethod,
    AST_PrivateSetter,
    AST_PrivateIn,
    AST_RegExp,
    AST_Return,
    AST_Sequence,
    AST_String,
    AST_Sub,
    AST_Super,
    AST_Switch,
    AST_Symbol,
    AST_SymbolClassProperty,
    AST_SymbolExportForeign,
    AST_SymbolImportForeign,
    AST_SymbolRef,
    AST_SymbolDeclaration,
    AST_TemplateSegment,
    AST_TemplateString,
    AST_This,
    AST_Throw,
    AST_Toplevel,
    AST_True,
    AST_Try,
    AST_Catch,
    AST_Finally,
    AST_Unary,
    AST_Undefined,
    AST_Var,
    AST_VarDef,
    AST_While,
    AST_With,
    AST_Yield,
    walk_parent
} from "./ast.js";
import { first_in_statement } from "./utils/first_in_statement.js";

let mangle_options = undefined;
AST_Node.prototype.size = function (compressor, stack) {
    mangle_options = compressor && compressor._mangle_options;

    let size = 0;
    walk_parent(this, (node, info) => {
        size += node._size(info);

        // Braceless arrow functions have fake "return" statements
        if (node instanceof AST_Arrow && node.is_braceless()) {
            size += node.body[0].value._size(info);
            return true;
        }
    }, stack || (compressor && compressor.stack));

    // just to save a bit of memory
    mangle_options = undefined;

    return size;
};

AST_Node.prototype._size = () => 0;

AST_Debugger.prototype._size = () => 8;

AST_Directive.prototype._size = function () {
    // TODO string encoding stuff
    return 2 + this.value.length;
};

/** Count commas/semicolons necessary to show a list of expressions/statements */
const list_overhead = (array) => array.length && array.length - 1;

AST_Block.prototype._size = function () {
    return 2 + list_overhead(this.body);
};

AST_Toplevel.prototype._size = function() {
    return list_overhead(this.body);
};

AST_EmptyStatement.prototype._size = () => 1;

AST_LabeledStatement.prototype._size = () => 2;  // x:

AST_Do.prototype._size = () => 9;

AST_While.prototype._size = () => 7;

AST_For.prototype._size = () => 8;

AST_ForIn.prototype._size = () => 8;
// AST_ForOf inherits ^

AST_With.prototype._size = () => 6;

AST_Expansion.prototype._size = () => 3;

const lambda_modifiers = func =>
    (func.is_generator ? 1 : 0) + (func.async ? 6 : 0);

AST_Accessor.prototype._size = function () {
    return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body);
};

AST_Function.prototype._size = function (info) {
    const first = !!first_in_statement(info);
    return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body);
};

AST_Defun.prototype._size = function () {
    return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body);
};

AST_Arrow.prototype._size = function () {
    let args_and_arrow = 2 + list_overhead(this.argnames);

    if (
        !(
            this.argnames.length === 1
            && this.argnames[0] instanceof AST_Symbol
        )
    ) {
        args_and_arrow += 2; // parens around the args
    }

    const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2;

    return lambda_modifiers(this) + args_and_arrow + body_overhead;
};

AST_Destructuring.prototype._size = () => 2;

AST_TemplateString.prototype._size = function () {
    return 2 + (Math.floor(this.segments.length / 2) * 3);  /* "${}" */
};

AST_TemplateSegment.prototype._size = function () {
    return this.value.length;
};

AST_Return.prototype._size = function () {
    return this.value ? 7 : 6;
};

AST_Throw.prototype._size = () => 6;

AST_Break.prototype._size = function () {
    return this.label ? 6 : 5;
};

AST_Continue.prototype._size = function () {
    return this.label ? 9 : 8;
};

AST_If.prototype._size = () => 4;

AST_Switch.prototype._size = function () {
    return 8 + list_overhead(this.body);
};

AST_Case.prototype._size = function () {
    return 5 + list_overhead(this.body);
};

AST_Default.prototype._size = function () {
    return 8 + list_overhead(this.body);
};

AST_Try.prototype._size = () => 3;

AST_Catch.prototype._size = function () {
    let size = 7 + list_overhead(this.body);
    if (this.argname) {
        size += 2;
    }
    return size;
};

AST_Finally.prototype._size = function () {
    return 7 + list_overhead(this.body);
};

AST_Var.prototype._size = function () {
    return 4 + list_overhead(this.definitions);
};

AST_Let.prototype._size = function () {
    return 4 + list_overhead(this.definitions);
};

AST_Const.prototype._size = function () {
    return 6 + list_overhead(this.definitions);
};

AST_VarDef.prototype._size = function () {
    return this.value ? 1 : 0;
};

AST_NameMapping.prototype._size = function () {
    // foreign name isn't mangled
    return this.name ? 4 : 0;
};

AST_Import.prototype._size = function () {
    // import
    let size = 6;

    if (this.imported_name) size += 1;

    // from
    if (this.imported_name || this.imported_names) size += 5;

    // braces, and the commas
    if (this.imported_names) {
        size += 2 + list_overhead(this.imported_names);
    }

    return size;
};

AST_ImportMeta.prototype._size = () => 11;

AST_Export.prototype._size = function () {
    let size = 7 + (this.is_default ? 8 : 0);

    if (this.exported_value) {
        size += this.exported_value._size();
    }

    if (this.exported_names) {
        // Braces and commas
        size += 2 + list_overhead(this.exported_names);
    }

    if (this.module_name) {
        // "from "
        size += 5;
    }

    return size;
};

AST_Call.prototype._size = function () {
    if (this.optional) {
        return 4 + list_overhead(this.args);
    }
    return 2 + list_overhead(this.args);
};

AST_New.prototype._size = function () {
    return 6 + list_overhead(this.args);
};

AST_Sequence.prototype._size = function () {
    return list_overhead(this.expressions);
};

AST_Dot.prototype._size = function () {
    if (this.optional) {
        return this.property.length + 2;
    }
    return this.property.length + 1;
};

AST_DotHash.prototype._size = function () {
    if (this.optional) {
        return this.property.length + 3;
    }
    return this.property.length + 2;
};

AST_Sub.prototype._size = function () {
    return this.optional ? 4 : 2;
};

AST_Unary.prototype._size = function () {
    if (this.operator === "typeof") return 7;
    if (this.operator === "void") return 5;
    return this.operator.length;
};

AST_Binary.prototype._size = function (info) {
    if (this.operator === "in") return 4;

    let size = this.operator.length;

    if (
        (this.operator === "+" || this.operator === "-")
        && this.right instanceof AST_Unary && this.right.operator === this.operator
    ) {
        // 1+ +a > needs space between the +
        size += 1;
    }

    if (this.needs_parens(info)) {
        size += 2;
    }

    return size;
};

AST_Conditional.prototype._size = () => 3;

AST_Array.prototype._size = function () {
    return 2 + list_overhead(this.elements);
};

AST_Object.prototype._size = function (info) {
    let base = 2;
    if (first_in_statement(info)) {
        base += 2; // parens
    }
    return base + list_overhead(this.properties);
};

/*#__INLINE__*/
const key_size = key =>
    typeof key === "string" ? key.length : 0;

AST_ObjectKeyVal.prototype._size = function () {
    return key_size(this.key) + 1;
};

/*#__INLINE__*/
const static_size = is_static => is_static ? 7 : 0;

AST_ObjectGetter.prototype._size = function () {
    return 5 + static_size(this.static) + key_size(this.key);
};

AST_ObjectSetter.prototype._size = function () {
    return 5 + static_size(this.static) + key_size(this.key);
};

AST_ConciseMethod.prototype._size = function () {
    return static_size(this.static) + key_size(this.key) + lambda_modifiers(this);
};

AST_PrivateMethod.prototype._size = function () {
    return AST_ConciseMethod.prototype._size.call(this) + 1;
};

AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () {
    return AST_ConciseMethod.prototype._size.call(this) + 4;
};

AST_PrivateIn.prototype._size = function () {
    return 5; // "#", and " in "
};

AST_Class.prototype._size = function () {
    return (
        (this.name ? 8 : 7)
        + (this.extends ? 8 : 0)
    );
};

AST_ClassStaticBlock.prototype._size = function () {
    // "static{}" + semicolons
    return 8 + list_overhead(this.body);
};

AST_ClassProperty.prototype._size = function () {
    return (
        static_size(this.static)
        + (typeof this.key === "string" ? this.key.length + 2 : 0)
        + (this.value ? 1 : 0)
    );
};

AST_ClassPrivateProperty.prototype._size = function () {
    return AST_ClassProperty.prototype._size.call(this) + 1;
};

AST_Symbol.prototype._size = function () {
    if (!(mangle_options && this.thedef && !this.thedef.unmangleable(mangle_options))) {
        return this.name.length;
    } else {
        return 1;
    }
};

// TODO take propmangle into account
AST_SymbolClassProperty.prototype._size = function () {
    return this.name.length;
};

AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () {
    if (this.name === "arguments") return 9;

    return AST_Symbol.prototype._size.call(this);
};

AST_NewTarget.prototype._size = () => 10;

AST_SymbolImportForeign.prototype._size = function () {
    return this.name.length;
};

AST_SymbolExportForeign.prototype._size = function () {
    return this.name.length;
};

AST_This.prototype._size = () => 4;

AST_Super.prototype._size = () => 5;

AST_String.prototype._size = function () {
    return this.value.length + 2;
};

AST_Number.prototype._size = function () {
    const { value } = this;
    if (value === 0) return 1;
    if (value > 0 && Math.floor(value) === value) {
        return Math.floor(Math.log10(value) + 1);
    }
    return value.toString().length;
};

AST_BigInt.prototype._size = function () {
    return this.value.length;
};

AST_RegExp.prototype._size = function () {
    return this.value.toString().length;
};

AST_Null.prototype._size = () => 4;

AST_NaN.prototype._size = () => 3;

AST_Undefined.prototype._size = () => 6; // "void 0"

AST_Hole.prototype._size = () => 0;  // comma is taken into account by list_overhead()

AST_Infinity.prototype._size = () => 8;

AST_True.prototype._size = () => 4;

AST_False.prototype._size = () => 5;

AST_Await.prototype._size = () => 6;

AST_Yield.prototype._size = () => 6;

license: mit


code:
/***********************************************************************

  A JavaScript tokenizer / parser / beautifier / compressor.
  https://github.com/mishoo/UglifyJS2

  -------------------------------- (C) ---------------------------------

                           Author: Mihai Bazon
                         <mihai.bazon@gmail.com>
                       http://mihai.bazon.net/blog

  Distributed under the BSD license:

    Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

        * Redistributions of source code must retain the above
          copyright notice, this list of conditions and the following
          disclaimer.

        * Redistributions in binary form must reproduce the above
          copyright notice, this list of conditions and the following
          disclaimer in the documentation and/or other materials
          provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.

 ***********************************************************************/

"use strict";

import {SourceMapConsumer, SourceMapGenerator} from "@jridgewell/source-map";
import {defaults, HOP} from "./utils/index.js";

// a small wrapper around source-map and @jridgewell/source-map
function* SourceMap(options) {
    options = defaults(options, {
        file : null,
        root : null,
        orig : null,
        files: {},
    });

    var orig_map;
    var generator = new SourceMapGenerator({
        file       : options.file,
        sourceRoot : options.root
    });

    let sourcesContent = {__proto__: null};
    let files = options.files;
    for (var name in files) if (HOP(files, name)) {
        sourcesContent[name] = files[name];
    }
    if (options.orig) {
        // We support both @jridgewell/source-map (which has a sync
        // SourceMapConsumer) and source-map (which has an async
        // SourceMapConsumer).
        orig_map = yield new SourceMapConsumer(options.orig);
        if (orig_map.sourcesContent) {
            orig_map.sources.forEach(function(source, i) {
                var content = orig_map.sourcesContent[i];
                if (content) {
                    sourcesContent[source] = content;
                }
            });
        }
    }

    function add(source, gen_line, gen_col, orig_line, orig_col, name) {
        let generatedPos = { line: gen_line, column: gen_col };

        if (orig_map) {
            var info = orig_map.originalPositionFor({
                line: orig_line,
                column: orig_col
            });
            if (info.source === null) {
                generator.addMapping({
                    generated: generatedPos,
                    original: null,
                    source: null,
                    name: null
                });
                return;
            }
            source = info.source;
            orig_line = info.line;
            orig_col = info.column;
            name = info.name || name;
        }
        generator.addMapping({
            generated : generatedPos,
            original  : { line: orig_line, column: orig_col },
            source    : source,
            name      : name
        });
        generator.setSourceContent(source, sourcesContent[source]);
    }

    function clean(map) {
        const allNull = map.sourcesContent && map.sourcesContent.every(c => c == null);
        if (allNull) delete map.sourcesContent;
        if (map.file === undefined) delete map.file;
        if (map.sourceRoot === undefined) delete map.sourceRoot;
        return map;
    }

    function getDecoded() {
        if (!generator.toDecodedMap) return null;
        return clean(generator.toDecodedMap());
    }

    function getEncoded() {
        return clean(generator.toJSON());
    }

    function destroy() {
        // @jridgewell/source-map's SourceMapConsumer does not need to be
        // manually freed.
        if (orig_map && orig_map.destroy) orig_map.destroy();
    }

    return {
        add,
        getDecoded,
        getEncoded,
        destroy,
    };
}

export {
    SourceMap,
};


code:
/***********************************************************************

  A JavaScript tokenizer / parser / beautifier / compressor.
  https://github.com/mishoo/UglifyJS2

  -------------------------------- (C) ---------------------------------

                           Author: Mihai Bazon
                         <mihai.bazon@gmail.com>
                       http://mihai.bazon.net/blog

  Distributed under the BSD license:

    Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

        * Redistributions of source code must retain the above
          copyright notice, this list of conditions and the following
          disclaimer.

        * Redistributions in binary form must reproduce the above
          copyright notice, this list of conditions and the following
          disclaimer in the documentation and/or other materials
          provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.

 ***********************************************************************/

"use strict";

import {
    AST_Array,
    AST_Await,
    AST_Binary,
    AST_PrivateIn,
    AST_Block,
    AST_Call,
    AST_Case,
    AST_Catch,
    AST_Chain,
    AST_Class,
    AST_ClassStaticBlock,
    AST_Conditional,
    AST_Definitions,
    AST_Destructuring,
    AST_Do,
    AST_Exit,
    AST_Expansion,
    AST_Export,
    AST_For,
    AST_ForIn,
    AST_If,
    AST_Import,
    AST_LabeledStatement,
    AST_Lambda,
    AST_LoopControl,
    AST_NameMapping,
    AST_Node,
    AST_Number,
    AST_Object,
    AST_ObjectProperty,
    AST_PrefixedTemplateString,
    AST_PropAccess,
    AST_Sequence,
    AST_SimpleStatement,
    AST_Sub,
    AST_Switch,
    AST_TemplateString,
    AST_Try,
    AST_Unary,
    AST_VarDef,
    AST_While,
    AST_With,
    AST_Yield,
} from "./ast.js";
import {
    MAP as do_list,
    noop,
} from "./utils/index.js";

function def_transform(node, descend) {
    node.DEFMETHOD("transform", function(tw, in_list) {
        let transformed = undefined;
        tw.push(this);
        if (tw.before) transformed = tw.before(this, descend, in_list);
        if (transformed === undefined) {
            transformed = this;
            descend(transformed, tw);
            if (tw.after) {
                const after_ret = tw.after(transformed, in_list);
                if (after_ret !== undefined) transformed = after_ret;
            }
        }
        tw.pop();
        return transformed;
    });
}

def_transform(AST_Node, noop);

def_transform(AST_LabeledStatement, function(self, tw) {
    self.label = self.label.transform(tw);
    self.body = self.body.transform(tw);
});

def_transform(AST_SimpleStatement, function(self, tw) {
    self.body = self.body.transform(tw);
});

def_transform(AST_Block, function(self, tw) {
    self.body = do_list(self.body, tw);
});

def_transform(AST_Do, function(self, tw) {
    self.body = self.body.transform(tw);
    self.condition = self.condition.transform(tw);
});

def_transform(AST_While, function(self, tw) {
    self.condition = self.condition.transform(tw);
    self.body = self.body.transform(tw);
});

def_transform(AST_For, function(self, tw) {
    if (self.init) self.init = self.init.transform(tw);
    if (self.condition) self.condition = self.condition.transform(tw);
    if (self.step) self.step = self.step.transform(tw);
    self.body = self.body.transform(tw);
});

def_transform(AST_ForIn, function(self, tw) {
    self.init = self.init.transform(tw);
    self.object = self.object.transform(tw);
    self.body = self.body.transform(tw);
});

def_transform(AST_With, function(self, tw) {
    self.expression = self.expression.transform(tw);
    self.body = self.body.transform(tw);
});

def_transform(AST_Exit, function(self, tw) {
    if (self.value) self.value = self.value.transform(tw);
});

def_transform(AST_LoopControl, function(self, tw) {
    if (self.label) self.label = self.label.transform(tw);
});

def_transform(AST_If, function(self, tw) {
    self.condition = self.condition.transform(tw);
    self.body = self.body.transform(tw);
    if (self.alternative) self.alternative = self.alternative.transform(tw);
});

def_transform(AST_Switch, function(self, tw) {
    self.expression = self.expression.transform(tw);
    self.body = do_list(self.body, tw);
});

def_transform(AST_Case, function(self, tw) {
    self.expression = self.expression.transform(tw);
    self.body = do_list(self.body, tw);
});

def_transform(AST_Try, function(self, tw) {
    self.body = self.body.transform(tw);
    if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
    if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
});

def_transform(AST_Catch, function(self, tw) {
    if (self.argname) self.argname = self.argname.transform(tw);
    self.body = do_list(self.body, tw);
});

def_transform(AST_Definitions, function(self, tw) {
    self.definitions = do_list(self.definitions, tw);
});

def_transform(AST_VarDef, function(self, tw) {
    self.name = self.name.transform(tw);
    if (self.value) self.value = self.value.transform(tw);
});

def_transform(AST_Destructuring, function(self, tw) {
    self.names = do_list(self.names, tw);
});

def_transform(AST_Lambda, function(self, tw) {
    if (self.name) self.name = self.name.transform(tw);
    self.argnames = do_list(self.argnames, tw, /* allow_splicing */ false);
    if (self.body instanceof AST_Node) {
        self.body = self.body.transform(tw);
    } else {
        self.body = do_list(self.body, tw);
    }
});

def_transform(AST_Call, function(self, tw) {
    self.expression = self.expression.transform(tw);
    self.args = do_list(self.args, tw, /* allow_splicing */ false);
});

def_transform(AST_Sequence, function(self, tw) {
    const result = do_list(self.expressions, tw);
    self.expressions = result.length
        ? result
        : [new AST_Number({ value: 0 })];
});

def_transform(AST_PropAccess, function(self, tw) {
    self.expression = self.expression.transform(tw);
});

def_transform(AST_Sub, function(self, tw) {
    self.expression = self.expression.transform(tw);
    self.property = self.property.transform(tw);
});

def_transform(AST_Chain, function(self, tw) {
    self.expression = self.expression.transform(tw);
});

def_transform(AST_Yield, function(self, tw) {
    if (self.expression) self.expression = self.expression.transform(tw);
});

def_transform(AST_Await, function(self, tw) {
    self.expression = self.expression.transform(tw);
});

def_transform(AST_Unary, function(self, tw) {
    self.expression = self.expression.transform(tw);
});

def_transform(AST_Binary, function(self, tw) {
    self.left = self.left.transform(tw);
    self.right = self.right.transform(tw);
});

def_transform(AST_PrivateIn, function(self, tw) {
    self.key = self.key.transform(tw);
    self.value = self.value.transform(tw);
});

def_transform(AST_Conditional, function(self, tw) {
    self.condition = self.condition.transform(tw);
    self.consequent = self.consequent.transform(tw);
    self.alternative = self.alternative.transform(tw);
});

def_transform(AST_Array, function(self, tw) {
    self.elements = do_list(self.elements, tw);
});

def_transform(AST_Object, function(self, tw) {
    self.properties = do_list(self.properties, tw);
});

def_transform(AST_ObjectProperty, function(self, tw) {
    if (self.key instanceof AST_Node) {
        self.key = self.key.transform(tw);
    }
    if (self.value) self.value = self.value.transform(tw);
});

def_transform(AST_Class, function(self, tw) {
    if (self.name) self.name = self.name.transform(tw);
    if (self.extends) self.extends = self.extends.transform(tw);
    self.properties = do_list(self.properties, tw);
});

def_transform(AST_ClassStaticBlock, function(self, tw) {
    self.body = do_list(self.body, tw);
});

def_transform(AST_Expansion, function(self, tw) {
    self.expression = self.expression.transform(tw);
});

def_transform(AST_NameMapping, function(self, tw) {
    self.foreign_name = self.foreign_name.transform(tw);
    self.name = self.name.transform(tw);
});

def_transform(AST_Import, function(self, tw) {
    if (self.imported_name) self.imported_name = self.imported_name.transform(tw);
    if (self.imported_names) do_list(self.imported_names, tw);
    self.module_name = self.module_name.transform(tw);
});

def_transform(AST_Export, function(self, tw) {
    if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw);
    if (self.exported_value) self.exported_value = self.exported_value.transform(tw);
    if (self.exported_names) do_list(self.exported_names, tw);
    if (self.module_name) self.module_name = self.module_name.transform(tw);
});

def_transform(AST_TemplateString, function(self, tw) {
    self.segments = do_list(self.segments, tw);
});

def_transform(AST_PrefixedTemplateString, function(self, tw) {
    self.prefix = self.prefix.transform(tw);
    self.template_string = self.template_string.transform(tw);
});


code:
import {
    AST_Binary,
    AST_Conditional,
    AST_Chain,
    AST_Dot,
    AST_Object,
    AST_Sequence,
    AST_Statement,
    AST_Sub,
    AST_UnaryPostfix,
    AST_PrefixedTemplateString
} from "../ast.js";

// return true if the node at the top of the stack (that means the
// innermost node in the current output) is lexically the first in
// a statement.
function first_in_statement(stack) {
    let node = stack.parent(-1);
    for (let i = 0, p; p = stack.parent(i); i++) {
        if (p instanceof AST_Statement && p.body === node)
            return true;
        if ((p instanceof AST_Sequence && p.expressions[0] === node) ||
            (p.TYPE === "Call" && p.expression === node) ||
            (p instanceof AST_PrefixedTemplateString && p.prefix === node) ||
            (p instanceof AST_Dot && p.expression === node) ||
            (p instanceof AST_Sub && p.expression === node) ||
            (p instanceof AST_Chain && p.expression === node) ||
            (p instanceof AST_Conditional && p.condition === node) ||
            (p instanceof AST_Binary && p.left === node) ||
            (p instanceof AST_UnaryPostfix && p.expression === node)
        ) {
            node = p;
        } else {
            return false;
        }
    }
}

// Returns whether the leftmost item in the expression is an object
function left_is_object(node) {
    if (node instanceof AST_Object) return true;
    if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]);
    if (node.TYPE === "Call") return left_is_object(node.expression);
    if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix);
    if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression);
    if (node instanceof AST_Chain) return left_is_object(node.expression);
    if (node instanceof AST_Conditional) return left_is_object(node.condition);
    if (node instanceof AST_Binary) return left_is_object(node.left);
    if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression);
    return false;
}

export { first_in_statement, left_is_object };


code:
/***********************************************************************

  A JavaScript tokenizer / parser / beautifier / compressor.
  https://github.com/mishoo/UglifyJS2

  -------------------------------- (C) ---------------------------------

                           Author: Mihai Bazon
                         <mihai.bazon@gmail.com>
                       http://mihai.bazon.net/blog

  Distributed under the BSD license:

    Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

        * Redistributions of source code must retain the above
          copyright notice, this list of conditions and the following
          disclaimer.

        * Redistributions in binary form must reproduce the above
          copyright notice, this list of conditions and the following
          disclaimer in the documentation and/or other materials
          provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.

 ***********************************************************************/

"use strict";

import { AST_Node } from "../ast.js";

function characters(str) {
    return str.split("");
}

function member(name, array) {
    return array.includes(name);
}

class DefaultsError extends Error {
    constructor(msg, defs) {
        super();

        this.name = "DefaultsError";
        this.message = msg;
        this.defs = defs;
    }
}

function defaults(args, defs, croak) {
    if (args === true) {
        args = {};
    } else if (args != null && typeof args === "object") {
        args = {...args};
    }

    const ret = args || {};

    if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) {
        throw new DefaultsError("`" + i + "` is not a supported option", defs);
    }

    for (const i in defs) if (HOP(defs, i)) {
        if (!args || !HOP(args, i)) {
            ret[i] = defs[i];
        } else if (i === "ecma") {
            let ecma = args[i] | 0;
            if (ecma > 5 && ecma < 2015) ecma += 2009;
            ret[i] = ecma;
        } else {
            ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
        }
    }

    return ret;
}

function noop() {}
function return_false() { return false; }
function return_true() { return true; }
function return_this() { return this; }
function return_null() { return null; }

var MAP = (function() {
    function MAP(a, tw, allow_splicing = true) {
        const new_a = [];

        for (let i = 0; i < a.length; ++i) {
            let item = a[i];
            let ret = item.transform(tw, allow_splicing);

            if (ret instanceof AST_Node) {
                new_a.push(ret);
            } else if (ret instanceof Splice) {
                new_a.push(...ret.v);
            }
        }

        return new_a;
    }

    MAP.splice = function(val) { return new Splice(val); };
    MAP.skip = {};
    function Splice(val) { this.v = val; }
    return MAP;
})();

function make_node(ctor, orig, props) {
    if (!props) props = {};
    if (orig) {
        if (!props.start) props.start = orig.start;
        if (!props.end) props.end = orig.end;
    }
    return new ctor(props);
}

function push_uniq(array, el) {
    if (!array.includes(el))
        array.push(el);
}

function string_template(text, props) {
    return text.replace(/{(.+?)}/g, function(str, p) {
        return props && props[p];
    });
}

function remove(array, el) {
    for (var i = array.length; --i >= 0;) {
        if (array[i] === el) array.splice(i, 1);
    }
}

function mergeSort(array, cmp) {
    if (array.length < 2) return array.slice();
    function merge(a, b) {
        var r = [], ai = 0, bi = 0, i = 0;
        while (ai < a.length && bi < b.length) {
            cmp(a[ai], b[bi]) <= 0
                ? r[i++] = a[ai++]
                : r[i++] = b[bi++];
        }
        if (ai < a.length) r.push.apply(r, a.slice(ai));
        if (bi < b.length) r.push.apply(r, b.slice(bi));
        return r;
    }
    function _ms(a) {
        if (a.length <= 1)
            return a;
        var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
        left = _ms(left);
        right = _ms(right);
        return merge(left, right);
    }
    return _ms(array);
}

function makePredicate(words) {
    if (!Array.isArray(words)) words = words.split(" ");

    return new Set(words.sort());
}

function map_add(map, key, value) {
    if (map.has(key)) {
        map.get(key).push(value);
    } else {
        map.set(key, [ value ]);
    }
}

function map_from_object(obj) {
    var map = new Map();
    for (var key in obj) {
        if (HOP(obj, key) && key.charAt(0) === "$") {
            map.set(key.substr(1), obj[key]);
        }
    }
    return map;
}

function map_to_object(map) {
    var obj = Object.create(null);
    map.forEach(function (value, key) {
        obj["$" + key] = value;
    });
    return obj;
}

function HOP(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
}

function keep_name(keep_setting, name) {
    return keep_setting === true
        || (keep_setting instanceof RegExp && keep_setting.test(name));
}

var lineTerminatorEscape = {
    "\0": "0",
    "\n": "n",
    "\r": "r",
    "\u2028": "u2028",
    "\u2029": "u2029",
};
function regexp_source_fix(source) {
    // V8 does not escape line terminators in regexp patterns in node 12
    // We'll also remove literal \0
    return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) {
        var escaped = source[offset - 1] == "\\"
            && (source[offset - 2] != "\\"
            || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1)));
        return (escaped ? "" : "\\") + lineTerminatorEscape[match];
    });
}

// Subset of regexps that is not going to cause regexp based DDOS
// https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
const re_safe_regexp = /^[\\/|\0\s\w^$.[\]()]*$/;

/** Check if the regexp is safe for Terser to create without risking a RegExp DOS */
export const regexp_is_safe = (source) => re_safe_regexp.test(source);

const all_flags = "dgimsuyv";
function sort_regexp_flags(flags) {
    const existing_flags = new Set(flags.split(""));
    let out = "";
    for (const flag of all_flags) {
        if (existing_flags.has(flag)) {
            out += flag;
            existing_flags.delete(flag);
        }
    }
    if (existing_flags.size) {
        // Flags Terser doesn't know about
        existing_flags.forEach(flag => { out += flag; });
    }
    return out;
}

function has_annotation(node, annotation) {
    return node._annotations & annotation;
}

function set_annotation(node, annotation) {
    node._annotations |= annotation;
}

function clear_annotation(node, annotation) {
    node._annotations &= ~annotation;
}

export {
    characters,
    defaults,
    HOP,
    keep_name,
    make_node,
    makePredicate,
    map_add,
    map_from_object,
    map_to_object,
    MAP,
    member,
    mergeSort,
    noop,
    push_uniq,
    regexp_source_fix,
    remove,
    return_false,
    return_null,
    return_this,
    return_true,
    sort_regexp_flags,
    string_template,
    has_annotation,
    set_annotation,
    clear_annotation,
};


code:
import "./lib/transform.js";
import "./lib/mozilla-ast.js";
import { minify } from "./lib/minify.js";

export { minify, minify_sync } from "./lib/minify.js";
export { run_cli as _run_cli } from "./lib/cli.js";

export async function _default_options() {
    const defs = {};

    Object.keys(infer_options({ 0: 0 })).forEach((component) => {
        const options = infer_options({
            [component]: {0: 0}
        });

        if (options) defs[component] = options;
    });
    return defs;
}

async function infer_options(options) {
    try {
        await minify("", options);
    } catch (error) {
        return error.defs;
    }
}


code:
2.20.3 / 2019-10-11
==================

  * Support Node.js 0.10 (Revert #1059)
  * Ran "npm unpublish commander@2.20.2". There is no 2.20.2.

2.20.1 / 2019-09-29
==================

  * Improve executable subcommand tracking
  * Update dev dependencies

2.20.0 / 2019-04-02
==================

  * fix: resolve symbolic links completely when hunting for subcommands (#935)
  * Update index.d.ts (#930)
  * Update Readme.md (#924)
  * Remove --save option as it isn't required anymore (#918)
  * Add link to the license file (#900)
  * Added example of receiving args from options (#858)
  * Added missing semicolon (#882)
  * Add extension to .eslintrc (#876)

2.19.0 / 2018-10-02
==================

  * Removed newline after Options and Commands headers (#864)
  * Bugfix - Error output (#862)
  * Fix to change default value to string (#856)

2.18.0 / 2018-09-07
==================

  * Standardize help output (#853)
  * chmod 644 travis.yml (#851)
  * add support for execute typescript subcommand via ts-node (#849)

2.17.1 / 2018-08-07
==================

  * Fix bug in command emit (#844)

2.17.0 / 2018-08-03
==================

  * fixed newline output after help information (#833)
  * Fix to emit the action even without command (#778)
  * npm update (#823)

2.16.0 / 2018-06-29
==================

  * Remove Makefile and `test/run` (#821)
  * Make 'npm test' run on Windows (#820)
  * Add badge to display install size (#807)
  * chore: cache node_modules (#814)
  * chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
  * fixed typo in readme (#812)
  * Fix types (#804)
  * Update eslint to resolve vulnerabilities in lodash (#799)
  * updated readme with custom event listeners. (#791)
  * fix tests (#794)

2.15.0 / 2018-03-07
==================

  * Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
  * Arguments description

2.14.1 / 2018-02-07
==================

  * Fix typing of help function

2.14.0 / 2018-02-05
==================

  * only register the option:version event once
  * Fixes issue #727: Passing empty string for option on command is set to undefined
  * enable eqeqeq rule
  * resolves #754 add linter configuration to project
  * resolves #560 respect custom name for version option
  * document how to override the version flag
  * document using options per command

2.13.0 / 2018-01-09
==================

  * Do not print default for --no-
  * remove trailing spaces in command help
  * Update CI's Node.js to LTS and latest version
  * typedefs: Command and Option types added to commander namespace

2.12.2 / 2017-11-28
==================

  * fix: typings are not shipped

2.12.1 / 2017-11-23
==================

  * Move @types/node to dev dependency

2.12.0 / 2017-11-22
==================

  * add attributeName() method to Option objects
  * Documentation updated for options with --no prefix
  * typings: `outputHelp` takes a string as the first parameter
  * typings: use overloads
  * feat(typings): update to match js api
  * Print default value in option help
  * Fix translation error
  * Fail when using same command and alias (#491)
  * feat(typings): add help callback
  * fix bug when description is add after command with options (#662)
  * Format js code
  * Rename History.md to CHANGELOG.md (#668)
  * feat(typings): add typings to support TypeScript (#646)
  * use current node

2.11.0 / 2017-07-03
==================

  * Fix help section order and padding (#652)
  * feature: support for signals to subcommands (#632)
  * Fixed #37, --help should not display first (#447)
  * Fix translation errors. (#570)
  * Add package-lock.json
  * Remove engines
  * Upgrade package version
  * Prefix events to prevent conflicts between commands and options (#494)
  * Removing dependency on graceful-readlink
  * Support setting name in #name function and make it chainable
  * Add .vscode directory to .gitignore (Visual Studio Code metadata)
  * Updated link to ruby commander in readme files

2.10.0 / 2017-06-19
==================

  * Update .travis.yml. drop support for older node.js versions.
  * Fix require arguments in README.md
  * On SemVer you do not start from 0.0.1
  * Add missing semi colon in readme
  * Add save param to npm install
  * node v6 travis test
  * Update Readme_zh-CN.md
  * Allow literal '--' to be passed-through as an argument
  * Test subcommand alias help
  * link build badge to master branch
  * Support the alias of Git style sub-command
  * added keyword commander for better search result on npm
  * Fix Sub-Subcommands
  * test node.js stable
  * Fixes TypeError when a command has an option called `--description`
  * Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
  * Add chinese Readme file

2.9.0 / 2015-10-13
==================

  * Add option `isDefault` to set default subcommand #415 @Qix-
  * Add callback to allow filtering or post-processing of help text #434 @djulien
  * Fix `undefined` text in help information close #414 #416 @zhiyelee

2.8.1 / 2015-04-22
==================

 * Back out `support multiline description` Close #396 #397

2.8.0 / 2015-04-07
==================

  * Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
  * Fix bug in Git-style sub-commands #372 @zhiyelee
  * Allow commands to be hidden from help #383 @tonylukasavage
  * When git-style sub-commands are in use, yet none are called, display help #382 @claylo
  * Add ability to specify arguments syntax for top-level command #258 @rrthomas
  * Support multiline descriptions #208 @zxqfox

2.7.1 / 2015-03-11
==================

 * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.

2.7.0 / 2015-03-09
==================

 * Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
 * Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
 * Add support for camelCase on `opts()`. Close #353  @nkzawa
 * Add node.js 0.12 and io.js to travis.yml
 * Allow RegEx options. #337 @palanik
 * Fixes exit code when sub-command failing.  Close #260 #332 @pirelenito
 * git-style `bin` files in $PATH make sense. Close #196 #327  @zhiyelee

2.6.0 / 2014-12-30
==================

  * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
  * Add application description to the help msg. Close #112 @dalssoft

2.5.1 / 2014-12-15
==================

  * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee

2.5.0 / 2014-10-24
==================

 * add support for variadic arguments. Closes #277 @whitlockjc

2.4.0 / 2014-10-17
==================

 * fixed a bug on executing the coercion function of subcommands option. Closes #270
 * added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
 * added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
 * fixed a bug on subcommand name. Closes #248 @jonathandelgado
 * fixed function normalize doesn’t honor option terminator. Closes #216 @abbr

2.3.0 / 2014-07-16
==================

 * add command alias'. Closes PR #210
 * fix: Typos. Closes #99
 * fix: Unused fs module. Closes #217

2.2.0 / 2014-03-29
==================

 * add passing of previous option value
 * fix: support subcommands on windows. Closes #142
 * Now the defaultValue passed as the second argument of the coercion function.

2.1.0 / 2013-11-21
==================

 * add: allow cflag style option params, unit test, fixes #174

2.0.0 / 2013-07-18
==================

 * remove input methods (.prompt, .confirm, etc)

1.3.2 / 2013-07-18
==================

 * add support for sub-commands to co-exist with the original command

1.3.1 / 2013-07-18
==================

 * add quick .runningCommand hack so you can opt-out of other logic when running a sub command

1.3.0 / 2013-07-09
==================

 * add EACCES error handling
 * fix sub-command --help

1.2.0 / 2013-06-13
==================

 * allow "-" hyphen as an option argument
 * support for RegExp coercion

1.1.1 / 2012-11-20
==================

  * add more sub-command padding
  * fix .usage() when args are present. Closes #106

1.1.0 / 2012-11-16
==================

  * add git-style executable subcommand support. Closes #94

1.0.5 / 2012-10-09
==================

  * fix `--name` clobbering. Closes #92
  * fix examples/help. Closes #89

1.0.4 / 2012-09-03
==================

  * add `outputHelp()` method.

1.0.3 / 2012-08-30
==================

  * remove invalid .version() defaulting

1.0.2 / 2012-08-24
==================

  * add `--foo=bar` support [arv]
  * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]

1.0.1 / 2012-08-03
==================

  * fix issue #56
  * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())

1.0.0 / 2012-07-05
==================

  * add support for optional option descriptions
  * add defaulting of `.version()` to package.json's version

0.6.1 / 2012-06-01
==================

  * Added: append (yes or no) on confirmation
  * Added: allow node.js v0.7.x

0.6.0 / 2012-04-10
==================

  * Added `.prompt(obj, callback)` support. Closes #49
  * Added default support to .choose(). Closes #41
  * Fixed the choice example

0.5.1 / 2011-12-20
==================

  * Fixed `password()` for recent nodes. Closes #36

0.5.0 / 2011-12-04
==================

  * Added sub-command option support [itay]

0.4.3 / 2011-12-04
==================

  * Fixed custom help ordering. Closes #32

0.4.2 / 2011-11-24
==================

  * Added travis support
  * Fixed: line-buffered input automatically trimmed. Closes #31

0.4.1 / 2011-11-18
==================

  * Removed listening for "close" on --help

0.4.0 / 2011-11-15
==================

  * Added support for `--`. Closes #24

0.3.3 / 2011-11-14
==================

  * Fixed: wait for close event when writing help info [Jerry Hamlet]

0.3.2 / 2011-11-01
==================

  * Fixed long flag definitions with values [felixge]

0.3.1 / 2011-10-31
==================

  * Changed `--version` short flag to `-V` from `-v`
  * Changed `.version()` so it's configurable [felixge]

0.3.0 / 2011-10-31
==================

  * Added support for long flags only. Closes #18

0.2.1 / 2011-10-24
==================

  * "node": ">= 0.4.x < 0.7.0". Closes #20

0.2.0 / 2011-09-26
==================

  * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]

0.1.0 / 2011-08-24
==================

  * Added support for custom `--help` output

0.0.5 / 2011-08-18
==================

  * Changed: when the user enters nothing prompt for password again
  * Fixed issue with passwords beginning with numbers [NuckChorris]

0.0.4 / 2011-08-15
==================

  * Fixed `Commander#args`

0.0.3 / 2011-08-15
==================

  * Added default option value support

0.0.2 / 2011-08-15
==================

  * Added mask support to `Command#password(str[, mask], fn)`
  * Added `Command#password(str, fn)`

0.0.1 / 2010-01-03
==================

  * Initial release


code:
# Commander.js

[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

  The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
  [API documentation](http://tj.github.com/commander.js/)

## Installation

    $ npm install commander

## Option parsing

Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.

```js
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var program = require('commander');

program
  .version('0.1.0')
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-b, --bbq-sauce', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  .parse(process.argv);

console.log('you ordered a pizza with:');
if (program.peppers) console.log('  - peppers');
if (program.pineapple) console.log('  - pineapple');
if (program.bbqSauce) console.log('  - bbq');
console.log('  - %s cheese', program.cheese);
```

Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.

Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.

```js
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var program = require('commander');

program
  .option('--no-sauce', 'Remove sauce')
  .parse(process.argv);

console.log('you ordered a pizza');
if (program.sauce) console.log('  with sauce');
else console.log(' without sauce');
```

To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.

e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```

Then to access the input if it was passed in.

e.g. ```var myInput = program.myarg```

**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.

## Version option

Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.

    $ ./examples/pizza -V
    0.0.1

If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.

```js
program
  .version('0.0.1', '-v, --version')
```

The version flags can be named anything, but the long option is required.

## Command-specific options

You can attach options to a command.

```js
#!/usr/bin/env node

var program = require('commander');

program
  .command('rm <dir>')
  .option('-r, --recursive', 'Remove recursively')
  .action(function (dir, cmd) {
    console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
  })

program.parse(process.argv)
```

A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.

## Coercion

```js
function range(val) {
  return val.split('..').map(Number);
}

function list(val) {
  return val.split(',');
}

function collect(val, memo) {
  memo.push(val);
  return memo;
}

function increaseVerbosity(v, total) {
  return total + 1;
}

program
  .version('0.1.0')
  .usage('[options] <file ...>')
  .option('-i, --integer <n>', 'An integer argument', parseInt)
  .option('-f, --float <n>', 'A float argument', parseFloat)
  .option('-r, --range <a>..<b>', 'A range', range)
  .option('-l, --list <items>', 'A list', list)
  .option('-o, --optional [value]', 'An optional value')
  .option('-c, --collect [value]', 'A repeatable value', collect, [])
  .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
  .parse(process.argv);

console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```

## Regular Expression
```js
program
  .version('0.1.0')
  .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
  .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
  .parse(process.argv);

console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```

## Variadic arguments

 The last argument of a command can be variadic, and only the last argument.  To make an argument variadic you have to
 append `...` to the argument name.  Here is an example:

```js
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var program = require('commander');

program
  .version('0.1.0')
  .command('rmdir <dir> [otherDirs...]')
  .action(function (dir, otherDirs) {
    console.log('rmdir %s', dir);
    if (otherDirs) {
      otherDirs.forEach(function (oDir) {
        console.log('rmdir %s', oDir);
      });
    }
  });

program.parse(process.argv);
```

 An `Array` is used for the value of a variadic argument.  This applies to `program.args` as well as the argument passed
 to your action as demonstrated above.

## Specify the argument syntax

```js
#!/usr/bin/env node

var program = require('commander');

program
  .version('0.1.0')
  .arguments('<cmd> [env]')
  .action(function (cmd, env) {
     cmdValue = cmd;
     envValue = env;
  });

program.parse(process.argv);

if (typeof cmdValue === 'undefined') {
   console.error('no command given!');
   process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.

## Git-style sub-commands

```js
// file: ./examples/pm
var program = require('commander');

program
  .version('0.1.0')
  .command('install [name]', 'install one or more packages')
  .command('search [query]', 'search with optional query')
  .command('list', 'list packages installed', {isDefault: true})
  .parse(process.argv);
```

When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.

Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.

If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.

### `--harmony`

You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.

## Automated --help

 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:

```
$ ./examples/pizza --help
Usage: pizza [options]

An application for pizzas ordering

Options:
  -h, --help           output usage information
  -V, --version        output the version number
  -p, --peppers        Add peppers
  -P, --pineapple      Add pineapple
  -b, --bbq            Add bbq sauce
  -c, --cheese <type>  Add the specified type of cheese [marble]
  -C, --no-cheese      You do not want any cheese
```

## Custom help

 You can display arbitrary `-h, --help` information
 by listening for "--help". Commander will automatically
 exit once you are done so that the remainder of your program
 does not execute causing undesired behaviors, for example
 in the following executable "stuff" will not output when
 `--help` is used.

```js
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var program = require('commander');

program
  .version('0.1.0')
  .option('-f, --foo', 'enable some foo')
  .option('-b, --bar', 'enable some bar')
  .option('-B, --baz', 'enable some baz');

// must be before .parse() since
// node's emit() is immediate

program.on('--help', function(){
  console.log('')
  console.log('Examples:');
  console.log('  $ custom-help --help');
  console.log('  $ custom-help -h');
});

program.parse(process.argv);

console.log('stuff');
```

Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:

```
Usage: custom-help [options]

Options:
  -h, --help     output usage information
  -V, --version  output the version number
  -f, --foo      enable some foo
  -b, --bar      enable some bar
  -B, --baz      enable some baz

Examples:
  $ custom-help --help
  $ custom-help -h
```

## .outputHelp(cb)

Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.

If you want to display help by default (e.g. if no command was provided), you can use something like:

```js
var program = require('commander');
var colors = require('colors');

program
  .version('0.1.0')
  .command('getstream [url]', 'get stream URL')
  .parse(process.argv);

if (!process.argv.slice(2).length) {
  program.outputHelp(make_red);
}

function make_red(txt) {
  return colors.red(txt); //display the help text in red on the console
}
```

## .help(cb)

  Output help information and exit immediately.
  Optional callback cb allows post-processing of help text before it is displayed.

## Custom event listeners
 You can execute custom actions by listening to command and option events.

```js
program.on('option:verbose', function () {
  process.env.VERBOSE = this.verbose;
});

// error on unknown commands
program.on('command:*', function () {
  console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
  process.exit(1);
});
```

## Examples

```js
var program = require('commander');

program
  .version('0.1.0')
  .option('-C, --chdir <path>', 'change the working directory')
  .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
  .option('-T, --no-tests', 'ignore test hook');

program
  .command('setup [env]')
  .description('run setup commands for all envs')
  .option("-s, --setup_mode [mode]", "Which setup mode to use")
  .action(function(env, options){
    var mode = options.setup_mode || "normal";
    env = env || 'all';
    console.log('setup for %s env(s) with %s mode', env, mode);
  });

program
  .command('exec <cmd>')
  .alias('ex')
  .description('execute the given remote cmd')
  .option("-e, --exec_mode <mode>", "Which exec mode to use")
  .action(function(cmd, options){
    console.log('exec "%s" using %s mode', cmd, options.exec_mode);
  }).on('--help', function() {
    console.log('');
    console.log('Examples:');
    console.log('');
    console.log('  $ deploy exec sequential');
    console.log('  $ deploy exec async');
  });

program
  .command('*')
  .action(function(env){
    console.log('deploying "%s"', env);
  });

program.parse(process.argv);
```

More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.

## License

[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)