#!/usr/bin/env node
'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var path = require('path');
var path__default = _interopDefault(path);
var module$1 = _interopDefault(require('module'));
var rollup = require('../dist/rollup.js');
var rollup__default = _interopDefault(rollup);
var assert = _interopDefault(require('assert'));
var events = _interopDefault(require('events'));
var fs = require('fs');
var fs__default = _interopDefault(fs);

var help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-v, --version               Show version number\n-h, --help                  Show this help message\n-c, --config                Use this config file (if argument is used but value\n                              is unspecified, defaults to rollup.config.js)\n-w, --watch                 Watch files in bundle and rebuild on changes\n-i, --input                 Input (alternative to <entry file>)\n-o, --file <output>         Output (if absent, prints to stdout)\n-f, --format [es]           Type of output (amd, cjs, es, iife, umd)\n-e, --external              Comma-separate list of module IDs to exclude\n-g, --globals               Comma-separate list of `module ID:Global` pairs\n                              Any module IDs defined here are added to external\n-n, --name                  Name for UMD export\n-m, --sourcemap             Generate sourcemap (`-m inline` for inline map)\n--amd.id                    ID for AMD module (default is anonymous)\n--amd.define                Function to use in place of `define`\n--no-strict                 Don't emit a `\"use strict\";` in the generated modules.\n--no-indent                 Don't indent result\n--environment <values>      Settings passed to config file (see example)\n--no-conflict               Generate a noConflict method for UMD globals\n--no-treeshake              Disable tree-shaking\n--silent                    Don't print warnings\n--intro                     Content to insert at top of bundle (inside wrapper)\n--outro                     Content to insert at end of bundle (inside wrapper)\n--banner                    Content to insert at top of bundle (outside wrapper)\n--footer                    Content to insert at end of bundle (outside wrapper)\n--no-interop                Do not include interop block\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n  -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";

var minimist = function (args, opts) {
    if (!opts) opts = {};
    
    var flags = { bools : {}, strings : {}, unknownFn: null };

    if (typeof opts['unknown'] === 'function') {
        flags.unknownFn = opts['unknown'];
    }

    if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
      flags.allBools = true;
    } else {
      [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
          flags.bools[key] = true;
      });
    }
    
    var aliases = {};
    Object.keys(opts.alias || {}).forEach(function (key) {
        aliases[key] = [].concat(opts.alias[key]);
        aliases[key].forEach(function (x) {
            aliases[x] = [key].concat(aliases[key].filter(function (y) {
                return x !== y;
            }));
        });
    });

    [].concat(opts.string).filter(Boolean).forEach(function (key) {
        flags.strings[key] = true;
        if (aliases[key]) {
            flags.strings[aliases[key]] = true;
        }
     });

    var defaults = opts['default'] || {};
    
    var argv = { _ : [] };
    Object.keys(flags.bools).forEach(function (key) {
        setArg(key, defaults[key] === undefined ? false : defaults[key]);
    });
    
    var notFlags = [];

    if (args.indexOf('--') !== -1) {
        notFlags = args.slice(args.indexOf('--')+1);
        args = args.slice(0, args.indexOf('--'));
    }

    function argDefined(key, arg) {
        return (flags.allBools && /^--[^=]+$/.test(arg)) ||
            flags.strings[key] || flags.bools[key] || aliases[key];
    }

    function setArg (key, val, arg) {
        if (arg && flags.unknownFn && !argDefined(key, arg)) {
            if (flags.unknownFn(arg) === false) return;
        }

        var value = !flags.strings[key] && isNumber(val)
            ? Number(val) : val
        ;
        setKey(argv, key.split('.'), value);
        
        (aliases[key] || []).forEach(function (x) {
            setKey(argv, x.split('.'), value);
        });
    }

    function setKey (obj, keys, value) {
        var o = obj;
        keys.slice(0,-1).forEach(function (key) {
            if (o[key] === undefined) o[key] = {};
            o = o[key];
        });

        var key = keys[keys.length - 1];
        if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
            o[key] = value;
        }
        else if (Array.isArray(o[key])) {
            o[key].push(value);
        }
        else {
            o[key] = [ o[key], value ];
        }
    }
    
    function aliasIsBoolean(key) {
      return aliases[key].some(function (x) {
          return flags.bools[x];
      });
    }

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        
        if (/^--.+=/.test(arg)) {
            // Using [\s\S] instead of . because js doesn't support the
            // 'dotall' regex modifier. See:
            // http://stackoverflow.com/a/1068308/13216
            var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
            var key = m[1];
            var value = m[2];
            if (flags.bools[key]) {
                value = value !== 'false';
            }
            setArg(key, value, arg);
        }
        else if (/^--no-.+/.test(arg)) {
            var key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false, arg);
        }
        else if (/^--.+/.test(arg)) {
            var key = arg.match(/^--(.+)/)[1];
            var next = args[i + 1];
            if (next !== undefined && !/^-/.test(next)
            && !flags.bools[key]
            && !flags.allBools
            && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                setArg(key, next, arg);
                i++;
            }
            else if (/^(true|false)$/.test(next)) {
                setArg(key, next === 'true', arg);
                i++;
            }
            else {
                setArg(key, flags.strings[key] ? '' : true, arg);
            }
        }
        else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1,-1).split('');
            
            var broken = false;
            for (var j = 0; j < letters.length; j++) {
                var next = arg.slice(j+2);
                
                if (next === '-') {
                    setArg(letters[j], next, arg);
                    continue;
                }
                
                if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
                    setArg(letters[j], next.split('=')[1], arg);
                    broken = true;
                    break;
                }
                
                if (/[A-Za-z]/.test(letters[j])
                && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letters[j], next, arg);
                    broken = true;
                    break;
                }
                
                if (letters[j+1] && letters[j+1].match(/\W/)) {
                    setArg(letters[j], arg.slice(j+2), arg);
                    broken = true;
                    break;
                }
                else {
                    setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
                }
            }
            
            var key = arg.slice(-1)[0];
            if (!broken && key !== '-') {
                if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
                && !flags.bools[key]
                && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                    setArg(key, args[i+1], arg);
                    i++;
                }
                else if (args[i+1] && /true|false/.test(args[i+1])) {
                    setArg(key, args[i+1] === 'true', arg);
                    i++;
                }
                else {
                    setArg(key, flags.strings[key] ? '' : true, arg);
                }
            }
        }
        else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
                argv._.push(
                    flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
                );
            }
            if (opts.stopEarly) {
                argv._.push.apply(argv._, args.slice(i + 1));
                break;
            }
        }
    }
    
    Object.keys(defaults).forEach(function (key) {
        if (!hasKey(argv, key.split('.'))) {
            setKey(argv, key.split('.'), defaults[key]);
            
            (aliases[key] || []).forEach(function (x) {
                setKey(argv, x.split('.'), defaults[key]);
            });
        }
    });
    
    if (opts['--']) {
        argv['--'] = new Array();
        notFlags.forEach(function(key) {
            argv['--'].push(key);
        });
    }
    else {
        notFlags.forEach(function(key) {
            argv._.push(key);
        });
    }

    return argv;
};

function hasKey (obj, keys) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        o = (o[key] || {});
    });

    var key = keys[keys.length - 1];
    return key in o;
}

function isNumber (x) {
    if (typeof x === 'number') return true;
    if (/^0x[0-9a-f]+$/i.test(x)) return true;
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

var version = "0.63.5";

const __assign = Object.assign || function (target) {
    for (var source, i = 1; i < arguments.length; i++) {
        source = arguments[i];
        for (var prop in source) {
            if (Object.prototype.hasOwnProperty.call(source, prop)) {
                target[prop] = source[prop];
            }
        }
    }
    return target;
};

function deprecateOptions(options, deprecateConfig) {
    var deprecations = [];
    if (deprecateConfig.input)
        deprecateInputOptions();
    if (deprecateConfig.output)
        deprecateOutputOptions();
    return deprecations;
    function deprecateInputOptions() {
        if (!options.input && options.entry)
            deprecate('entry', 'input');
        if (options.dest)
            deprecateToOutputOption('dest', 'file');
        if (options.moduleName)
            deprecateToOutputOption('moduleName', 'name');
        if (options.name)
            deprecateToOutputOption('name', 'name');
        if (options.extend)
            deprecateToOutputOption('extend', 'extend');
        if (options.globals)
            deprecateToOutputOption('globals', 'globals');
        if (options.indent)
            deprecateToOutputOption('indent', 'indent');
        if (options.noConflict)
            deprecateToOutputOption('noConflict', 'noConflict');
        if (options.paths)
            deprecateToOutputOption('paths', 'paths');
        if (options.sourcemap)
            deprecateToOutputOption('sourcemap', 'sourcemap');
        if (options.sourceMap)
            deprecateToOutputOption('sourceMap', 'sourcemap');
        if (options.sourceMapFile)
            deprecateToOutputOption('sourceMapFile', 'sourcemapFile');
        if (options.useStrict)
            deprecateToOutputOption('useStrict', 'strict');
        if (options.strict)
            deprecateToOutputOption('strict', 'strict');
        if (options.format)
            deprecateToOutputOption('format', 'format');
        if (options.banner)
            deprecateToOutputOption('banner', 'banner');
        if (options.footer)
            deprecateToOutputOption('footer', 'footer');
        if (options.intro)
            deprecateToOutputOption('intro', 'intro');
        if (options.outro)
            deprecateToOutputOption('outro', 'outro');
        if (options.interop)
            deprecateToOutputOption('interop', 'interop');
        if (options.freeze)
            deprecateToOutputOption('freeze', 'freeze');
        if (options.exports)
            deprecateToOutputOption('exports', 'exports');
        if (options.targets) {
            deprecations.push({ old: 'targets', new: 'output' });
            // as targets is an array and we need to merge other output options
            // like sourcemap etc.
            options.output = options.targets.map(function (target) { return (__assign({}, target, options.output)); });
            delete options.targets;
            var deprecatedDest_1 = false;
            options.output.forEach(function (outputEntry) {
                if (outputEntry.dest) {
                    if (!deprecatedDest_1) {
                        deprecations.push({ old: 'targets.dest', new: 'output.file' });
                        deprecatedDest_1 = true;
                    }
                    outputEntry.file = outputEntry.dest;
                    delete outputEntry.dest;
                }
            });
        }
        if (options.pureExternalModules) {
            deprecations.push({
                old: 'pureExternalModules',
                new: 'treeshake.pureExternalModules'
            });
            if (options.treeshake === undefined) {
                options.treeshake = {};
            }
            if (options.treeshake) {
                options.treeshake.pureExternalModules = options.pureExternalModules;
            }
            delete options.pureExternalModules;
        }
    }
    function deprecateOutputOptions() {
        if (options.output && options.output.moduleId) {
            options.output.amd = { id: options.moduleId };
            deprecations.push({ old: 'moduleId', new: 'amd' });
            delete options.output.moduleId;
        }
    }
    function deprecate(oldOption, newOption) {
        deprecations.push({ new: newOption, old: oldOption });
        if (!(newOption in options)) {
            options[newOption] = options[oldOption];
        }
        delete options[oldOption];
    }
    function deprecateToOutputOption(oldOption, newOption) {
        deprecations.push({ new: "output." + newOption, old: oldOption });
        options.output = options.output || {};
        if (!(newOption in options.output)) {
            options.output[newOption] = options[oldOption];
        }
        delete options[oldOption];
    }
}

function ensureArray(thing) {
    if (Array.isArray(thing))
        return thing;
    if (thing == undefined)
        return [];
    return [thing];
}

var createGetOption = function (config, command) { return function (name, defaultValue) {
    return command[name] !== undefined
        ? command[name]
        : config[name] !== undefined
            ? config[name]
            : defaultValue;
}; };
var normalizeObjectOptionValue = function (optionValue) {
    if (!optionValue) {
        return optionValue;
    }
    if (typeof optionValue !== 'object') {
        return {};
    }
    return optionValue;
};
var getObjectOption = function (config, command, name) {
    var commandOption = normalizeObjectOptionValue(command[name]);
    var configOption = normalizeObjectOptionValue(config[name]);
    if (commandOption !== undefined) {
        return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;
    }
    return configOption;
};
var defaultOnWarn = function (warning) {
    if (typeof warning === 'string') {
        console.warn(warning); // eslint-disable-line no-console
    }
    else {
        console.warn(warning.message); // eslint-disable-line no-console
    }
};
var getOnWarn = function (config, command, defaultOnWarnHandler) {
    if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }
    return command.silent
        ? function () { }
        : config.onwarn
            ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }
            : defaultOnWarnHandler;
};
var getExternal = function (config, command) {
    var configExternal = config.external;
    return typeof configExternal === 'function'
        ? function (id) {
            var rest = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                rest[_i - 1] = arguments[_i];
            }
            return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;
        }
        : (configExternal || []).concat(command.external);
};
var commandAliases = {
    c: 'config',
    e: 'external',
    f: 'format',
    g: 'globals',
    h: 'help',
    i: 'input',
    m: 'sourcemap',
    n: 'name',
    o: 'file',
    v: 'version',
    w: 'watch'
};
function mergeOptions(_a) {
    var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, deprecateConfig = _a.deprecateConfig, defaultOnWarnHandler = _a.defaultOnWarnHandler;
    var deprecations = deprecate(config, rawCommandOptions, deprecateConfig);
    var command = getCommandOptions(rawCommandOptions);
    var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
    if (command.output) {
        Object.assign(command, command.output);
    }
    var normalizedOutputOptions = ensureArray(config.output);
    if (normalizedOutputOptions.length === 0)
        normalizedOutputOptions.push({});
    var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {
        return getOutputOptions(singleOutputOptions, command);
    });
    var unknownOptionErrors = [];
    var validInputOptions = Object.keys(inputOptions);
    addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
    var validOutputOptions = Object.keys(outputOptions[0]);
    addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');
    addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
    return {
        inputOptions: inputOptions,
        outputOptions: outputOptions,
        deprecations: deprecations,
        optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null
    };
}
function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {
    if (ignoredKeys === void 0) { ignoredKeys = /$./; }
    var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });
    if (unknownOptions.length > 0)
        errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));
}
function getCommandOptions(rawCommandOptions) {
    var command = __assign({}, rawCommandOptions);
    command.external = (rawCommandOptions.external || '').split(',');
    if (rawCommandOptions.globals) {
        command.globals = Object.create(null);
        rawCommandOptions.globals.split(',').forEach(function (str) {
            var names = str.split(':');
            command.globals[names[0]] = names[1];
            // Add missing Module IDs to external.
            if (command.external.indexOf(names[0]) === -1) {
                command.external.push(names[0]);
            }
        });
    }
    return command;
}
function getInputOptions(config, command, defaultOnWarnHandler) {
    if (command === void 0) { command = {}; }
    var getOption = createGetOption(config, command);
    var inputOptions = {
        acorn: config.acorn,
        acornInjectPlugins: config.acornInjectPlugins,
        cache: getOption('cache'),
        context: config.context,
        experimentalCodeSplitting: getOption('experimentalCodeSplitting'),
        experimentalPreserveModules: getOption('experimentalPreserveModules'),
        experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
        external: getExternal(config, command),
        inlineDynamicImports: getOption('inlineDynamicImports', false),
        input: getOption('input'),
        manualChunks: getOption('manualChunks'),
        chunkGroupingSize: getOption('chunkGroupingSize', 5000),
        optimizeChunks: getOption('optimizeChunks'),
        moduleContext: config.moduleContext,
        onwarn: getOnWarn(config, command, defaultOnWarnHandler),
        perf: getOption('perf', false),
        plugins: config.plugins,
        preferConst: getOption('preferConst'),
        preserveSymlinks: getOption('preserveSymlinks'),
        treeshake: getObjectOption(config, command, 'treeshake'),
        shimMissingExports: getOption('shimMissingExports'),
        watch: config.watch
    };
    // legacy to make sure certain plugins still work
    if (Array.isArray(inputOptions.input)) {
        inputOptions.entry = inputOptions.input[0];
    }
    else if (typeof inputOptions.input === 'object') {
        for (var name in inputOptions.input) {
            inputOptions.entry = inputOptions.input[name];
            break;
        }
    }
    else {
        inputOptions.entry = inputOptions.input;
    }
    return inputOptions;
}
function getOutputOptions(config, command) {
    if (command === void 0) { command = {}; }
    var getOption = createGetOption(config, command);
    var format = getOption('format');
    return {
        amd: __assign({}, config.amd, command.amd),
        assetFileNames: getOption('assetFileNames'),
        banner: getOption('banner'),
        dir: getOption('dir'),
        chunkFileNames: getOption('chunkFileNames'),
        compact: getOption('compact', false),
        entryFileNames: getOption('entryFileNames'),
        esModule: getOption('esModule', true),
        exports: getOption('exports'),
        extend: getOption('extend'),
        file: getOption('file'),
        footer: getOption('footer'),
        format: format === 'esm' ? 'es' : format,
        freeze: getOption('freeze', true),
        globals: getOption('globals'),
        indent: getOption('indent', true),
        interop: getOption('interop', true),
        intro: getOption('intro'),
        name: getOption('name'),
        namespaceToStringTag: getOption('namespaceToStringTag', false),
        noConflict: getOption('noConflict'),
        outro: getOption('outro'),
        paths: getOption('paths'),
        sourcemap: getOption('sourcemap'),
        sourcemapFile: getOption('sourcemapFile'),
        strict: getOption('strict', true)
    };
}
function deprecate(config, command, deprecateConfig) {
    if (command === void 0) { command = {}; }
    if (deprecateConfig === void 0) { deprecateConfig = { input: true, output: true }; }
    var deprecations = [];
    // CLI
    if (command.id) {
        deprecations.push({
            old: '-u/--id',
            new: '--amd.id'
        });
        (command.amd || (command.amd = {})).id = command.id;
    }
    if (typeof command.output === 'string') {
        deprecations.push({
            old: '--output',
            new: '--file'
        });
        command.output = { file: command.output };
    }
    if (command.d) {
        deprecations.push({
            old: '-d',
            new: '--indent'
        });
        command.indent = command.d;
    }
    // config file
    deprecations.push.apply(deprecations, deprecateOptions(config, deprecateConfig));
    return deprecations;
}

var modules = {};

var getModule = function(dir) {
  var rootPath = dir ? path__default.resolve(dir) : process.cwd();
  var rootName = path__default.join(rootPath, '@root');
  var root = modules[rootName];
  if (!root) {
    root = new module$1(rootName);
    root.filename = rootName;
    root.paths = module$1._nodeModulePaths(rootPath);
    modules[rootName] = root;
  }
  return root;
};

var requireRelative = function(requested, relativeTo) {
  var root = getModule(relativeTo);
  return root.require(requested);
};

requireRelative.resolve = function(requested, relativeTo) {
  var root = getModule(relativeTo);
  return module$1._resolveFilename(requested, root);
};

var requireRelative_1 = requireRelative;

var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
function isAbsolute(path$$1) {
    return absolutePath.test(path$$1);
}

function getAliasName(resolved, unresolved) {
    var alias = path.basename(unresolved || resolved);
    var ext = path.extname(resolved);
    if (alias.endsWith(ext))
        alias = alias.substr(0, alias.length - ext.length);
    return alias;
}
function relativeId(id) {
    if (typeof process === 'undefined' || !isAbsolute(id))
        return id;
    return path.relative(process.cwd(), id);
}

const defineProperty = Object.defineProperty;

const Style = (open, close) => ({
  open: `\x1b[${open}m`,
  close: `\x1b[${close}m`,
  strip: new RegExp(`\\x1b\\[${close}m`, "g")
});

const Styles = {
  reset: Style(0, 0),
  bold: Style(1, 22),
  dim: Style(2, 22),
  italic: Style(3, 23),
  underline: Style(4, 24),
  inverse: Style(7, 27),
  hidden: Style(8, 28),
  strikethrough: Style(9, 29),

  black: Style(30, 39),
  red: Style(31, 39),
  green: Style(32, 39),
  yellow: Style(33, 39),
  blue: Style(34, 39),
  magenta: Style(35, 39),
  cyan: Style(36, 39),
  white: Style(37, 39),
  gray: Style(90, 39),

  bgBlack: Style(40, 49),
  bgRed: Style(101, 49),
  bgGreen: Style(102, 49),
  bgYellow: Style(103, 49),
  bgBlue: Style(104, 49),
  bgMagenta: Style(105, 49),
  bgCyan: Style(106, 49),
  bgWhite: Style(107, 49)
};

const turbocolor = {
  Styles,
  enabled:
    process.env.FORCE_COLOR ||
    process.platform === "win32" ||
    (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")
};

const color = function(out) {
  if (!turbocolor.enabled) return out

  let i, style;
  const names = this.names;
  const length = names.length;

  for (i = 0, out = out + ""; i < length; i++) {
    style = Styles[names[i]];
    out = `${style.open}${out.replace(style.strip, style.open)}${style.close}`;
  }

  return out
};

for (const name in Styles) {
  defineProperty(turbocolor, name, {
    get() {
      if (this.names === undefined) {
        const chain = {};
        const style = color.bind(chain);

        style.__proto__ = turbocolor;
        style.names = chain.names = [name];

        return style
      }

      this.names.push(name);
      return this
    }
  });
}

var turbocolor_1 = turbocolor;

// log to stderr to keep `rollup main.js > bundle.js` from breaking
var stderr = console.error.bind(console); // eslint-disable-line no-console
function handleError(err, recover) {
    if (recover === void 0) { recover = false; }
    var description = err.message || err;
    if (err.name)
        description = err.name + ": " + description;
    var message = (err.plugin
        ? "(" + err.plugin + " plugin) " + description
        : description) || err;
    stderr(turbocolor_1.bold.red("[!] " + turbocolor_1.bold(message.toString())));
    // TODO should this be "err.url || (err.file && err.loc.file) || err.id"?
    if (err.url) {
        stderr(turbocolor_1.cyan(err.url));
    }
    if (err.loc) {
        stderr(relativeId(err.loc.file || err.id) + " (" + err.loc.line + ":" + err.loc.column + ")");
    }
    else if (err.id) {
        stderr(relativeId(err.id));
    }
    if (err.frame) {
        stderr(turbocolor_1.dim(err.frame));
    }
    else if (err.stack) {
        stderr(turbocolor_1.dim(err.stack));
    }
    stderr('');
    if (!recover)
        process.exit(1);
}

function sequence(array, fn) {
    var results = [];
    var promise = Promise.resolve();
    function next(member, i) {
        return fn(member).then(function (value) { return (results[i] = value); });
    }
    var _loop_1 = function (i) {
        promise = promise.then(function () { return next(array[i], i); });
    };
    for (var i = 0; i < array.length; i += 1) {
        _loop_1(i);
    }
    return promise.then(function () { return results; });
}

function batchWarnings() {
    var allWarnings = new Map();
    var count = 0;
    return {
        get count() {
            return count;
        },
        add: function (warning) {
            if (typeof warning === 'string') {
                warning = { code: 'UNKNOWN', message: warning };
            }
            if (warning.code in immediateHandlers) {
                immediateHandlers[warning.code](warning);
                return;
            }
            if (!allWarnings.has(warning.code))
                allWarnings.set(warning.code, []);
            allWarnings.get(warning.code).push(warning);
            count += 1;
        },
        flush: function () {
            if (count === 0)
                return;
            var codes = Array.from(allWarnings.keys()).sort(function (a, b) {
                if (deferredHandlers[a] && deferredHandlers[b]) {
                    return deferredHandlers[a].priority - deferredHandlers[b].priority;
                }
                if (deferredHandlers[a])
                    return -1;
                if (deferredHandlers[b])
                    return 1;
                return allWarnings.get(b).length - allWarnings.get(a).length;
            });
            codes.forEach(function (code) {
                var handler = deferredHandlers[code];
                var warnings = allWarnings.get(code);
                if (handler) {
                    handler.fn(warnings);
                }
                else {
                    warnings.forEach(function (warning) {
                        stderr(turbocolor_1.bold.yellow('(!)') + " " + turbocolor_1.bold.yellow(warning.message));
                        if (warning.url)
                            info(warning.url);
                        var id = (warning.loc && warning.loc.file) || warning.id;
                        if (id) {
                            var loc = warning.loc
                                ? relativeId(id) + ": (" + warning.loc.line + ":" + warning.loc.column + ")"
                                : relativeId(id);
                            stderr(turbocolor_1.bold(relativeId(loc)));
                        }
                        if (warning.frame)
                            info(warning.frame);
                    });
                }
            });
            allWarnings = new Map();
            count = 0;
        }
    };
}
var immediateHandlers = {
    UNKNOWN_OPTION: function (warning) {
        title("You have passed an unrecognized option");
        stderr(warning.message);
    },
    DEPRECATED_OPTIONS: function (warning) {
        title("Some options have been renamed");
        info("https://gist.github.com/Rich-Harris/d472c50732dab03efeb37472b08a3f32");
        warning.deprecations.forEach(function (option) {
            stderr(turbocolor_1.bold(option.old) + " is now " + option.new);
        });
    },
    MISSING_NODE_BUILTINS: function (warning) {
        title("Missing shims for Node.js built-ins");
        var detail = warning.modules.length === 1
            ? "'" + warning.modules[0] + "'"
            : warning.modules
                .slice(0, -1)
                .map(function (name) { return "'" + name + "'"; })
                .join(', ') + " and '" + warning.modules.slice(-1) + "'";
        stderr("Creating a browser bundle that depends on " + detail + ". You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins");
    },
    MIXED_EXPORTS: function () {
        title('Mixing named and default exports');
        stderr("Consumers of your bundle will have to use bundle['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning");
    },
    EMPTY_BUNDLE: function () {
        title("Generated an empty bundle");
    }
};
// TODO select sensible priorities
var deferredHandlers = {
    UNUSED_EXTERNAL_IMPORT: {
        priority: 1,
        fn: function (warnings) {
            title('Unused external imports');
            warnings.forEach(function (warning) {
                stderr(warning.names + " imported from external module '" + warning.source + "' but never used");
            });
        }
    },
    UNRESOLVED_IMPORT: {
        priority: 1,
        fn: function (warnings) {
            title('Unresolved dependencies');
            info('https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency');
            var dependencies = new Map();
            warnings.forEach(function (warning) {
                if (!dependencies.has(warning.source))
                    dependencies.set(warning.source, []);
                dependencies.get(warning.source).push(warning.importer);
            });
            Array.from(dependencies.keys()).forEach(function (dependency) {
                var importers = dependencies.get(dependency);
                stderr(turbocolor_1.bold(dependency) + " (imported by " + importers.join(', ') + ")");
            });
        }
    },
    MISSING_EXPORT: {
        priority: 1,
        fn: function (warnings) {
            title('Missing exports');
            info('https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module');
            warnings.forEach(function (warning) {
                stderr(turbocolor_1.bold(warning.importer));
                stderr(warning.missing + " is not exported by " + warning.exporter);
                stderr(turbocolor_1.gray(warning.frame));
            });
        }
    },
    THIS_IS_UNDEFINED: {
        priority: 1,
        fn: function (warnings) {
            title('`this` has been rewritten to `undefined`');
            info('https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined');
            showTruncatedWarnings(warnings);
        }
    },
    EVAL: {
        priority: 1,
        fn: function (warnings) {
            title('Use of eval is strongly discouraged');
            info('https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval');
            showTruncatedWarnings(warnings);
        }
    },
    NON_EXISTENT_EXPORT: {
        priority: 1,
        fn: function (warnings) {
            title("Import of non-existent " + (warnings.length > 1 ? 'exports' : 'export'));
            showTruncatedWarnings(warnings);
        }
    },
    NAMESPACE_CONFLICT: {
        priority: 1,
        fn: function (warnings) {
            title("Conflicting re-exports");
            warnings.forEach(function (warning) {
                stderr(turbocolor_1.bold(relativeId(warning.reexporter)) + " re-exports '" + warning.name + "' from both " + relativeId(warning.sources[0]) + " and " + relativeId(warning.sources[1]) + " (will be ignored)");
            });
        }
    },
    MISSING_GLOBAL_NAME: {
        priority: 1,
        fn: function (warnings) {
            title("Missing global variable " + (warnings.length > 1 ? 'names' : 'name'));
            stderr("Use output.globals to specify browser global variable names corresponding to external modules");
            warnings.forEach(function (warning) {
                stderr(turbocolor_1.bold(warning.source) + " (guessing '" + warning.guess + "')");
            });
        }
    },
    SOURCEMAP_BROKEN: {
        priority: 1,
        fn: function (warnings) {
            title("Broken sourcemap");
            info('https://github.com/rollup/rollup/wiki/Troubleshooting#sourcemap-is-likely-to-be-incorrect');
            var plugins = Array.from(new Set(warnings.map(function (w) { return w.plugin; }).filter(Boolean)));
            var detail = plugins.length === 0
                ? ''
                : plugins.length > 1
                    ? " (such as " + plugins
                        .slice(0, -1)
                        .map(function (p) { return "'" + p + "'"; })
                        .join(', ') + " and '" + plugins.slice(-1) + "')"
                    : " (such as '" + plugins[0] + "')";
            stderr("Plugins that transform code" + detail + " should generate accompanying sourcemaps");
        }
    },
    PLUGIN_WARNING: {
        priority: 1,
        fn: function (warnings) {
            var nestedByPlugin = nest(warnings, 'plugin');
            nestedByPlugin.forEach(function (_a) {
                var plugin = _a.key, items = _a.items;
                var nestedByMessage = nest(items, 'message');
                var lastUrl;
                nestedByMessage.forEach(function (_a) {
                    var message = _a.key, items = _a.items;
                    title(plugin + " plugin: " + message);
                    items.forEach(function (warning) {
                        if (warning.url !== lastUrl)
                            info((lastUrl = warning.url));
                        var loc = warning.loc
                            ? relativeId(warning.id) + ": (" + warning.loc.line + ":" + warning.loc.column + ")"
                            : relativeId(warning.id);
                        stderr(turbocolor_1.bold(relativeId(loc)));
                        if (warning.frame)
                            info(warning.frame);
                    });
                });
            });
        }
    }
};
function title(str) {
    stderr(turbocolor_1.bold.yellow('(!)') + " " + turbocolor_1.bold.yellow(str));
}
function info(url) {
    stderr(turbocolor_1.gray(url));
}
function nest(array, prop) {
    var nested = [];
    var lookup = new Map();
    array.forEach(function (item) {
        var key = item[prop];
        if (!lookup.has(key)) {
            lookup.set(key, {
                key: key,
                items: []
            });
            nested.push(lookup.get(key));
        }
        lookup.get(key).items.push(item);
    });
    return nested;
}
function showTruncatedWarnings(warnings) {
    var nestedByModule = nest(warnings, 'id');
    var sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
    sliced.forEach(function (_a) {
        var id = _a.key, items = _a.items;
        stderr(turbocolor_1.bold(relativeId(id)));
        stderr(turbocolor_1.gray(items[0].frame));
        if (items.length > 1) {
            stderr("...and " + (items.length - 1) + " other " + (items.length > 2 ? 'occurrences' : 'occurrence'));
        }
    });
    if (nestedByModule.length > sliced.length) {
        stderr("\n...and " + (nestedByModule.length - sliced.length) + " other files");
    }
}

var parseMs = function (ms) {
	if (typeof ms !== 'number') {
		throw new TypeError('Expected a number');
	}

	var roundTowardZero = ms > 0 ? Math.floor : Math.ceil;

	return {
		days: roundTowardZero(ms / 86400000),
		hours: roundTowardZero(ms / 3600000) % 24,
		minutes: roundTowardZero(ms / 60000) % 60,
		seconds: roundTowardZero(ms / 1000) % 60,
		milliseconds: roundTowardZero(ms) % 1000
	};
};

const plur = (word, count) => count === 1 ? word : word + 's';

var prettyMs = (ms, opts) => {
	if (!Number.isFinite(ms)) {
		throw new TypeError('Expected a finite number');
	}

	opts = opts || {};

	if (ms < 1000) {
		const msDecimalDigits = typeof opts.msDecimalDigits === 'number' ? opts.msDecimalDigits : 0;
		return (msDecimalDigits ? ms.toFixed(msDecimalDigits) : Math.ceil(ms)) + (opts.verbose ? ' ' + plur('millisecond', Math.ceil(ms)) : 'ms');
	}

	const ret = [];

	const add = (val, long, short, valStr) => {
		if (val === 0) {
			return;
		}

		const postfix = opts.verbose ? ' ' + plur(long, val) : short;

		ret.push((valStr || val) + postfix);
	};

	const parsed = parseMs(ms);

	add(Math.trunc(parsed.days / 365), 'year', 'y');
	add(parsed.days % 365, 'day', 'd');
	add(parsed.hours, 'hour', 'h');
	add(parsed.minutes, 'minute', 'm');

	if (opts.compact) {
		add(parsed.seconds, 'second', 's');
		return '~' + ret[0];
	}

	const sec = ms / 1000 % 60;
	const secDecimalDigits = typeof opts.secDecimalDigits === 'number' ? opts.secDecimalDigits : 1;
	const secFixed = sec.toFixed(secDecimalDigits);
	const secStr = opts.keepDecimalsOnWholeSeconds ? secFixed : secFixed.replace(/\.0+$/, '');
	add(sec, 'second', 's', secStr);

	return ret.join(' ');
};

function mapSequence(array, fn) {
    var results = [];
    var promise = Promise.resolve();
    function next(member, i) {
        return Promise.resolve(fn(member)).then(function (value) { return (results[i] = value); });
    }
    var _loop_1 = function (i) {
        promise = promise.then(function () { return next(array[i], i); });
    };
    for (var i = 0; i < array.length; i += 1) {
        _loop_1(i);
    }
    return promise.then(function () { return results; });
}

var SOURCEMAPPING_URL = 'sourceMa';
SOURCEMAPPING_URL += 'ppingURL';
var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;

function printTimings(timings) {
    Object.keys(timings).forEach(function (label) {
        var color = label[0] === '#' ? (label[1] !== '#' ? turbocolor_1.underline : turbocolor_1.bold) : function (text) { return text; };
        console.info(color(label + ": " + timings[label].toFixed(0) + "ms"));
    });
}

function build(inputOptions, outputOptions, warnings, silent) {
    if (silent === void 0) { silent = false; }
    var useStdout = outputOptions.length === 1 &&
        !outputOptions[0].file &&
        !outputOptions[0].dir &&
        inputOptions.input instanceof Array === false &&
        typeof inputOptions.input !== 'object';
    var start = Date.now();
    var files = useStdout ? ['stdout'] : outputOptions.map(function (t) { return relativeId(t.file || t.dir); });
    if (!silent) {
        var inputFiles = void 0;
        if (typeof inputOptions.input === 'string') {
            inputFiles = inputOptions.input;
        }
        else if (inputOptions.input instanceof Array) {
            inputFiles = inputOptions.input.join(', ');
        }
        else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
            inputFiles = Object.keys(inputOptions.input)
                .map(function (name) { return inputOptions.input[name]; })
                .join(', ');
        }
        stderr(turbocolor_1.cyan("\n" + turbocolor_1.bold(inputFiles) + " \u2192 " + turbocolor_1.bold(files.join(', ')) + "..."));
    }
    return rollup.rollup(inputOptions)
        .then(function (bundle) {
        if (useStdout) {
            var output_1 = outputOptions[0];
            if (output_1.sourcemap && output_1.sourcemap !== 'inline') {
                handleError({
                    code: 'MISSING_OUTPUT_OPTION',
                    message: 'You must specify a --file (-o) option when creating a file with a sourcemap'
                });
            }
            return bundle.generate(output_1).then(function (_a) {
                var code = _a.code, map = _a.map;
                if (!code)
                    return;
                if (output_1.sourcemap === 'inline') {
                    code += "\n//# " + SOURCEMAPPING_URL$1 + "=" + map.toUrl() + "\n";
                }
                process.stdout.write(code);
            });
        }
        return mapSequence(outputOptions, function (output) { return bundle.write(output); }).then(function () { return bundle; });
    })
        .then(function (bundle) {
        warnings.flush();
        if (!silent)
            stderr(turbocolor_1.green("created " + turbocolor_1.bold(files.join(', ')) + " in " + turbocolor_1.bold(prettyMs(Date.now() - start))));
        if (bundle && bundle.getTimings) {
            printTimings(bundle.getTimings());
        }
    })
        .catch(handleError);
}

function loadConfigFile(configFile, commandOptions) {
    if (commandOptions === void 0) { commandOptions = {}; }
    var silent = commandOptions.silent || false;
    var warnings = batchWarnings();
    return rollup__default
        .rollup({
        input: configFile,
        external: function (id) {
            return (id[0] !== '.' && !path__default.isAbsolute(id)) || id.slice(-5, id.length) === '.json';
        },
        onwarn: warnings.add
    })
        .then(function (bundle) {
        if (!silent && warnings.count > 0) {
            stderr(turbocolor_1.bold("loaded " + relativeId(configFile) + " with warnings"));
            warnings.flush();
        }
        return bundle.generate({
            format: 'cjs'
        });
    })
        .then(function (_a) {
        var code = _a.code;
        // temporarily override require
        var defaultLoader = require.extensions['.js'];
        require.extensions['.js'] = function (module, filename) {
            if (filename === configFile) {
                module._compile(code, filename);
            }
            else {
                defaultLoader(module, filename);
            }
        };
        delete require.cache[configFile];
        return Promise.resolve(require(configFile))
            .then(function (configFileContent) {
            if (typeof configFileContent === 'function') {
                return configFileContent(commandOptions);
            }
            return configFileContent;
        })
            .then(function (configs) {
            if (Object.keys(configs).length === 0) {
                handleError({
                    code: 'MISSING_CONFIG',
                    message: 'Config file must export an options object, or an array of options objects',
                    url: 'https://rollupjs.org/#using-config-files'
                });
            }
            require.extensions['.js'] = defaultLoader;
            return Array.isArray(configs) ? configs : [configs];
        });
    });
}

var timeZone = date => {
	const offset = (date || new Date()).getTimezoneOffset();
	const absOffset = Math.abs(offset);
	const hours = Math.floor(absOffset / 60);
	const minutes = absOffset % 60;
	const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';

	return (offset < 0 ? '+' : '-') + hours + minutesOut;
};

var dateTime = options => {
	options = Object.assign({
		date: new Date(),
		local: true,
		showTimeZone: false,
		showMilliseconds: false
	}, options);

	let date = options.date;

	if (options.local) {
		// Offset the date so it will return the correct value when getting the ISO string
		date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
	}

	let end = '';

	if (options.showTimeZone) {
		end = ' UTC' + (options.local ? timeZone(date) : '');
	}

	if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {
		end = ` ${date.getUTCMilliseconds()}ms${end}`;
	}

	return date
		.toISOString()
		.replace(/T/, ' ')
		.replace(/\..+/, end);
};

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

var signals = createCommonjsModule(function (module) {
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems.  Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL.  It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
  'SIGABRT',
  'SIGALRM',
  'SIGHUP',
  'SIGINT',
  'SIGTERM'
];

if (process.platform !== 'win32') {
  module.exports.push(
    'SIGVTALRM',
    'SIGXCPU',
    'SIGXFSZ',
    'SIGUSR2',
    'SIGTRAP',
    'SIGSYS',
    'SIGQUIT',
    'SIGIOT'
    // should detect profiler and enable/disable accordingly.
    // see #21
    // 'SIGPROF'
  );
}

if (process.platform === 'linux') {
  module.exports.push(
    'SIGIO',
    'SIGPOLL',
    'SIGPWR',
    'SIGSTKFLT',
    'SIGUNUSED'
  );
}
});

// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.

var signals$1 = signals;

var EE = events;
/* istanbul ignore if */
if (typeof EE !== 'function') {
  EE = EE.EventEmitter;
}

var emitter;
if (process.__signal_exit_emitter__) {
  emitter = process.__signal_exit_emitter__;
} else {
  emitter = process.__signal_exit_emitter__ = new EE();
  emitter.count = 0;
  emitter.emitted = {};
}

// Because this emitter is a global, we have to check to see if a
// previous version of this library failed to enable infinite listeners.
// I know what you're about to say.  But literally everything about
// signal-exit is a compromise with evil.  Get used to it.
if (!emitter.infinite) {
  emitter.setMaxListeners(Infinity);
  emitter.infinite = true;
}

var signalExit = function (cb, opts) {
  assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');

  if (loaded === false) {
    load();
  }

  var ev = 'exit';
  if (opts && opts.alwaysLast) {
    ev = 'afterexit';
  }

  var remove = function () {
    emitter.removeListener(ev, cb);
    if (emitter.listeners('exit').length === 0 &&
        emitter.listeners('afterexit').length === 0) {
      unload();
    }
  };
  emitter.on(ev, cb);

  return remove
};

var unload_1 = unload;
function unload () {
  if (!loaded) {
    return
  }
  loaded = false;

  signals$1.forEach(function (sig) {
    try {
      process.removeListener(sig, sigListeners[sig]);
    } catch (er) {}
  });
  process.emit = originalProcessEmit;
  process.reallyExit = originalProcessReallyExit;
  emitter.count -= 1;
}

function emit (event, code, signal) {
  if (emitter.emitted[event]) {
    return
  }
  emitter.emitted[event] = true;
  emitter.emit(event, code, signal);
}

// { <signal>: <listener fn>, ... }
var sigListeners = {};
signals$1.forEach(function (sig) {
  sigListeners[sig] = function listener () {
    // If there are no other listeners, an exit is coming!
    // Simplest way: remove us and then re-send the signal.
    // We know that this will kill the process, so we can
    // safely emit now.
    var listeners = process.listeners(sig);
    if (listeners.length === emitter.count) {
      unload();
      emit('exit', null, sig);
      /* istanbul ignore next */
      emit('afterexit', null, sig);
      /* istanbul ignore next */
      process.kill(process.pid, sig);
    }
  };
});

var signals_1 = function () {
  return signals$1
};

var load_1 = load;

var loaded = false;

function load () {
  if (loaded) {
    return
  }
  loaded = true;

  // This is the number of onSignalExit's that are in play.
  // It's important so that we can count the correct number of
  // listeners on signals, and don't wait for the other one to
  // handle it instead of us.
  emitter.count += 1;

  signals$1 = signals$1.filter(function (sig) {
    try {
      process.on(sig, sigListeners[sig]);
      return true
    } catch (er) {
      return false
    }
  });

  process.emit = processEmit;
  process.reallyExit = processReallyExit;
}

var originalProcessReallyExit = process.reallyExit;
function processReallyExit (code) {
  process.exitCode = code || 0;
  emit('exit', process.exitCode, null);
  /* istanbul ignore next */
  emit('afterexit', process.exitCode, null);
  /* istanbul ignore next */
  originalProcessReallyExit.call(process, process.exitCode);
}

var originalProcessEmit = process.emit;
function processEmit (ev, arg) {
  if (ev === 'exit') {
    if (arg !== undefined) {
      process.exitCode = arg;
    }
    var ret = originalProcessEmit.apply(this, arguments);
    emit('exit', process.exitCode, null);
    /* istanbul ignore next */
    emit('afterexit', process.exitCode, null);
    return ret
  } else {
    return originalProcessEmit.apply(this, arguments)
  }
}
signalExit.unload = unload_1;
signalExit.signals = signals_1;
signalExit.load = load_1;

var ansiEscapes = createCommonjsModule(function (module) {
const x = module.exports;
const ESC = '\u001B[';
const OSC = '\u001B]';
const BEL = '\u0007';
const SEP = ';';
const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';

x.cursorTo = (x, y) => {
	if (typeof x !== 'number') {
		throw new TypeError('The `x` argument is required');
	}

	if (typeof y !== 'number') {
		return ESC + (x + 1) + 'G';
	}

	return ESC + (y + 1) + ';' + (x + 1) + 'H';
};

x.cursorMove = (x, y) => {
	if (typeof x !== 'number') {
		throw new TypeError('The `x` argument is required');
	}

	let ret = '';

	if (x < 0) {
		ret += ESC + (-x) + 'D';
	} else if (x > 0) {
		ret += ESC + x + 'C';
	}

	if (y < 0) {
		ret += ESC + (-y) + 'A';
	} else if (y > 0) {
		ret += ESC + y + 'B';
	}

	return ret;
};

x.cursorUp = count => ESC + (typeof count === 'number' ? count : 1) + 'A';
x.cursorDown = count => ESC + (typeof count === 'number' ? count : 1) + 'B';
x.cursorForward = count => ESC + (typeof count === 'number' ? count : 1) + 'C';
x.cursorBackward = count => ESC + (typeof count === 'number' ? count : 1) + 'D';

x.cursorLeft = ESC + 'G';
x.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');
x.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');
x.cursorGetPosition = ESC + '6n';
x.cursorNextLine = ESC + 'E';
x.cursorPrevLine = ESC + 'F';
x.cursorHide = ESC + '?25l';
x.cursorShow = ESC + '?25h';

x.eraseLines = count => {
	let clear = '';

	for (let i = 0; i < count; i++) {
		clear += x.eraseLine + (i < count - 1 ? x.cursorUp() : '');
	}

	if (count) {
		clear += x.cursorLeft;
	}

	return clear;
};

x.eraseEndLine = ESC + 'K';
x.eraseStartLine = ESC + '1K';
x.eraseLine = ESC + '2K';
x.eraseDown = ESC + 'J';
x.eraseUp = ESC + '1J';
x.eraseScreen = ESC + '2J';
x.scrollUp = ESC + 'S';
x.scrollDown = ESC + 'T';

x.clearScreen = '\u001Bc';
x.beep = BEL;

x.link = (text, url) => {
	return [
		OSC,
		'8',
		SEP,
		SEP,
		url,
		BEL,
		text,
		OSC,
		'8',
		SEP,
		SEP,
		BEL
	].join('');
};

x.image = (buf, opts) => {
	opts = opts || {};

	let ret = OSC + '1337;File=inline=1';

	if (opts.width) {
		ret += `;width=${opts.width}`;
	}

	if (opts.height) {
		ret += `;height=${opts.height}`;
	}

	if (opts.preserveAspectRatio === false) {
		ret += ';preserveAspectRatio=0';
	}

	return ret + ':' + buf.toString('base64') + BEL;
};

x.iTerm = {};

x.iTerm.setCwd = cwd => OSC + '50;CurrentDir=' + (cwd || process.cwd()) + BEL;
});

var SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';
var HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';
var isWindows = process.platform === 'win32';
var isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);
var isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';
var supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;
function alternateScreen(enabled) {
    if (!enabled) {
        var needAnnounce_1 = true;
        return {
            open: function () { },
            close: function () { },
            reset: function (heading) {
                if (needAnnounce_1) {
                    stderr(heading);
                    needAnnounce_1 = false;
                }
            }
        };
    }
    return {
        open: function () {
            if (supportsAnsi) {
                process.stderr.write(SHOW_ALTERNATE_SCREEN);
            }
        },
        close: function () {
            if (supportsAnsi) {
                process.stderr.write(HIDE_ALTERNATE_SCREEN);
            }
        },
        reset: function (heading) {
            stderr("" + ansiEscapes.eraseScreen + ansiEscapes.cursorTo(0, 0) + heading);
        }
    };
}

function watch(configFile, configs, command, silent) {
    if (silent === void 0) { silent = false; }
    var isTTY = Boolean(process.stderr.isTTY);
    var warnings = batchWarnings();
    var initialConfigs = processConfigs(configs);
    var clearScreen = initialConfigs.every(function (config) { return config.watch.clearScreen !== false; });
    var screen = alternateScreen(isTTY && clearScreen);
    screen.open();
    var watcher;
    var configWatcher;
    var processConfigsErr;
    function processConfigs(configs) {
        return configs.map(function (options) {
            var merged = mergeOptions({
                config: options,
                command: command,
                defaultOnWarnHandler: warnings.add
            });
            var result = __assign({}, merged.inputOptions, { output: merged.outputOptions });
            if (!result.watch)
                result.watch = {};
            if (merged.deprecations.length) {
                result.watch._deprecations = merged.deprecations;
            }
            if (merged.optionError)
                merged.inputOptions.onwarn({
                    message: merged.optionError,
                    code: 'UNKNOWN_OPTION'
                });
            if (merged.inputOptions.watch &&
                merged.inputOptions.watch.clearScreen === false) {
                processConfigsErr = stderr;
            }
            return result;
        });
    }
    function start(configs) {
        var screenWriter = processConfigsErr || screen.reset;
        watcher = rollup.watch(configs);
        watcher.on('event', function (event) {
            switch (event.code) {
                case 'FATAL':
                    screen.close();
                    handleError(event.error, true);
                    process.exit(1);
                    break;
                case 'ERROR':
                    warnings.flush();
                    handleError(event.error, true);
                    break;
                case 'START':
                    screenWriter(turbocolor_1.underline("rollup v" + rollup.VERSION));
                    break;
                case 'BUNDLE_START':
                    if (!silent) {
                        var input_1 = event.input;
                        if (typeof input_1 !== 'string') {
                            input_1 = Array.isArray(input_1)
                                ? input_1.join(', ')
                                : Object.keys(input_1)
                                    .map(function (key) { return input_1[key]; })
                                    .join(', ');
                        }
                        stderr(turbocolor_1.cyan("bundles " + turbocolor_1.bold(input_1) + " \u2192 " + turbocolor_1.bold(event.output.map(relativeId).join(', ')) + "..."));
                    }
                    break;
                case 'BUNDLE_END':
                    warnings.flush();
                    if (!silent)
                        stderr(turbocolor_1.green("created " + turbocolor_1.bold(event.output.map(relativeId).join(', ')) + " in " + turbocolor_1.bold(prettyMs(event.duration))));
                    if (event.result && event.result.getTimings) {
                        printTimings(event.result.getTimings());
                    }
                    break;
                case 'END':
                    if (!silent && isTTY) {
                        stderr("\n[" + dateTime() + "] waiting for changes...");
                    }
            }
        });
    }
    // catch ctrl+c, kill, and uncaught errors
    var removeOnExit = signalExit(close);
    process.on('uncaughtException', close);
    // only listen to stdin if it is a pipe
    if (!process.stdin.isTTY) {
        process.stdin.on('end', close); // in case we ever support stdin!
        process.stdin.resume();
    }
    function close(err) {
        removeOnExit();
        process.removeListener('uncaughtException', close);
        // removing a non-existent listener is a no-op
        process.stdin.removeListener('end', close);
        screen.close();
        if (watcher)
            watcher.close();
        if (configWatcher)
            configWatcher.close();
        if (err) {
            console.error(err);
            process.exit(1);
        }
    }
    try {
        start(initialConfigs);
    }
    catch (err) {
        close(err);
        return;
    }
    if (configFile && !configFile.startsWith('node:')) {
        var restarting_1 = false;
        var aborted_1 = false;
        var configFileData_1 = fs__default.readFileSync(configFile, 'utf-8');
        var restart_1 = function () {
            var newConfigFileData = fs__default.readFileSync(configFile, 'utf-8');
            if (newConfigFileData === configFileData_1)
                return;
            configFileData_1 = newConfigFileData;
            if (restarting_1) {
                aborted_1 = true;
                return;
            }
            restarting_1 = true;
            loadConfigFile(configFile, command)
                .then(function (_configs) {
                restarting_1 = false;
                if (aborted_1) {
                    aborted_1 = false;
                    restart_1();
                }
                else {
                    watcher.close();
                    start(initialConfigs);
                }
            })
                .catch(function (err) {
                handleError(err, true);
            });
        };
        configWatcher = fs__default.watch(configFile, function (event) {
            if (event === 'change')
                restart_1();
        });
    }
}

function runRollup(command) {
    if (command._.length >= 1) {
        if (command.input) {
            handleError({
                code: 'DUPLICATE_IMPORT_OPTIONS',
                message: 'use --input, or pass input path as argument'
            });
        }
    }
    if (command.dir) {
        if (command._.length && !command._.some(function (input) { return input.indexOf('=') !== -1; })) {
            command.input = command._;
        }
        else if (command._.length ||
            Array.isArray(command.input) ||
            typeof command.input === 'string') {
            var input = void 0;
            if (command._.length)
                input = command._;
            else
                input = typeof command.input === 'string' ? [command.input] : command.input;
            command.input = {};
            input.forEach(function (input) {
                var equalsIndex = input.indexOf('=');
                var value = input.substr(equalsIndex + 1);
                var key = input.substr(0, equalsIndex);
                if (!key)
                    key = getAliasName(input);
                command.input[key] = value;
            });
        }
        command._ = [];
    }
    else if (command._.length === 1) {
        command.input = command._[0];
    }
    if (command.environment) {
        var environment = Array.isArray(command.environment)
            ? command.environment
            : [command.environment];
        environment.forEach(function (arg) {
            arg.split(',').forEach(function (pair) {
                var _a = pair.split(':'), key = _a[0], value = _a[1];
                if (value) {
                    process.env[key] = value;
                }
                else {
                    process.env[key] = String(true);
                }
            });
        });
    }
    var configFile = command.config === true ? 'rollup.config.js' : command.config;
    if (configFile) {
        if (configFile.slice(0, 5) === 'node:') {
            var pkgName = configFile.slice(5);
            try {
                configFile = requireRelative_1.resolve("rollup-config-" + pkgName, process.cwd());
            }
            catch (err) {
                try {
                    configFile = requireRelative_1.resolve(pkgName, process.cwd());
                }
                catch (err) {
                    if (err.code === 'MODULE_NOT_FOUND') {
                        handleError({
                            code: 'MISSING_EXTERNAL_CONFIG',
                            message: "Could not resolve config file " + configFile
                        });
                    }
                    throw err;
                }
            }
        }
        else {
            // find real path of config so it matches what Node provides to callbacks in require.extensions
            configFile = fs.realpathSync(configFile);
        }
        if (command.watch)
            process.env.ROLLUP_WATCH = 'true';
        loadConfigFile(configFile, command)
            .then(function (configs) { return execute(configFile, configs, command); })
            .catch(handleError);
    }
    else {
        return execute(configFile, [{ input: null }], command);
    }
}
function execute(configFile, configs, command) {
    if (command.watch) {
        watch(configFile, configs, command, command.silent);
    }
    else {
        return sequence(configs, function (config) {
            var warnings = batchWarnings();
            var _a = mergeOptions({
                config: config,
                command: command,
                defaultOnWarnHandler: warnings.add
            }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions, deprecations = _a.deprecations, optionError = _a.optionError;
            if (deprecations.length) {
                inputOptions.onwarn({
                    code: 'DEPRECATED_OPTIONS',
                    message: "The following options have been renamed \u2014 please update your config: " + deprecations
                        .map(function (option) { return option.old + " -> " + option.new; })
                        .join(', '),
                    deprecations: deprecations
                });
            }
            if (optionError)
                inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });
            return build(inputOptions, outputOptions, warnings, command.silent);
        });
    }
}

var command = minimist(process.argv.slice(2), {
    alias: commandAliases
});
if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {
    console.log("\n" + help.replace('__VERSION__', version) + "\n"); // eslint-disable-line no-console
}
else if (command.version) {
    console.log("rollup version " + version); // eslint-disable-line no-console
}
else {
    try {
        require('source-map-support').install();
    }
    catch (err) {
        // do nothing
    }
    runRollup(command);
}
