UNPKG

65.4 kBPlain TextView Raw
1#!/usr/bin/env node
2'use strict';
3
4function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5
6var fs = require('fs');
7var fs__default = _interopDefault(fs);
8var path = require('path');
9var path__default = _interopDefault(path);
10var module$1 = _interopDefault(require('module'));
11var rollup = require('../dist/rollup.js');
12var rollup__default = _interopDefault(rollup);
13var assert = _interopDefault(require('assert'));
14var events = _interopDefault(require('events'));
15
16var help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-c, --config <filename> Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-d, --dir <dirname> Directory for chunks (if absent, prints to stdout)\n-e, --external <ids> Comma-separate list of module IDs to exclude\n-f, --format <format> Type of output (amd, cjs, esm, iife, umd)\n-g, --globals <pairs> Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input <filename> Input (alternative to <entry file>)\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name <name> Name for UMD export\n-o, --file <output> Single output file (if absent, prints to stdout)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.id <id> ID for AMD module (default is anonymous)\n--amd.define <name> Function to use in place of `define`\n--assetFileNames <pattern> Name pattern for emitted assets\n--banner <text> Code to insert at top of bundle (outside wrapper)\n--chunkFileNames <pattern> Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context <variable> Specify top-level `this` value\n--dynamicImportFunction <name> Rename the dynamic `import()` function\n--entryFileNames <pattern> Name pattern for emitted entry chunks\n--environment <values> Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports <mode> Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--no-freeze Do not freeze namespace objects\n--no-indent Don't indent result\n--no-interop Do not include interop block\n--inlineDynamicImports Create single bundle when using dynamic imports\n--intro <text> Code to insert at top of bundle (inside wrapper)\n--namespaceToStringTag Create proper `.toString` methods for namespaces\n--noConflict Generate a noConflict method for UMD globals\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--preferConst Use `const` instead of `var` for exports\n--preserveModules Preserve module structure\n--preserveSymlinks Do not follow symlinks when resolving files\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile <file> Specify bundle position for source maps\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--no-treeshake.propertyReadSideEffects Ignore property access side-effects\n--treeshake.pureExternalModules Assume side-effect free externals\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";
17
18var minimist = function (args, opts) {
19 if (!opts)
20 opts = {};
21 var flags = { bools: {}, strings: {}, unknownFn: null };
22 if (typeof opts['unknown'] === 'function') {
23 flags.unknownFn = opts['unknown'];
24 }
25 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
26 flags.allBools = true;
27 }
28 else {
29 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
30 flags.bools[key] = true;
31 });
32 }
33 var aliases = {};
34 Object.keys(opts.alias || {}).forEach(function (key) {
35 aliases[key] = [].concat(opts.alias[key]);
36 aliases[key].forEach(function (x) {
37 aliases[x] = [key].concat(aliases[key].filter(function (y) {
38 return x !== y;
39 }));
40 });
41 });
42 [].concat(opts.string).filter(Boolean).forEach(function (key) {
43 flags.strings[key] = true;
44 if (aliases[key]) {
45 flags.strings[aliases[key]] = true;
46 }
47 });
48 var defaults = opts['default'] || {};
49 var argv = { _: [] };
50 Object.keys(flags.bools).forEach(function (key) {
51 setArg(key, defaults[key] === undefined ? false : defaults[key]);
52 });
53 var notFlags = [];
54 if (args.indexOf('--') !== -1) {
55 notFlags = args.slice(args.indexOf('--') + 1);
56 args = args.slice(0, args.indexOf('--'));
57 }
58 function argDefined(key, arg) {
59 return (flags.allBools && /^--[^=]+$/.test(arg)) ||
60 flags.strings[key] || flags.bools[key] || aliases[key];
61 }
62 function setArg(key, val, arg) {
63 if (arg && flags.unknownFn && !argDefined(key, arg)) {
64 if (flags.unknownFn(arg) === false)
65 return;
66 }
67 var value = !flags.strings[key] && isNumber(val)
68 ? Number(val) : val;
69 setKey(argv, key.split('.'), value);
70 (aliases[key] || []).forEach(function (x) {
71 setKey(argv, x.split('.'), value);
72 });
73 }
74 function setKey(obj, keys, value) {
75 var o = obj;
76 keys.slice(0, -1).forEach(function (key) {
77 if (o[key] === undefined)
78 o[key] = {};
79 o = o[key];
80 });
81 var key = keys[keys.length - 1];
82 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
83 o[key] = value;
84 }
85 else if (Array.isArray(o[key])) {
86 o[key].push(value);
87 }
88 else {
89 o[key] = [o[key], value];
90 }
91 }
92 function aliasIsBoolean(key) {
93 return aliases[key].some(function (x) {
94 return flags.bools[x];
95 });
96 }
97 for (var i = 0; i < args.length; i++) {
98 var arg = args[i];
99 if (/^--.+=/.test(arg)) {
100 // Using [\s\S] instead of . because js doesn't support the
101 // 'dotall' regex modifier. See:
102 // http://stackoverflow.com/a/1068308/13216
103 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
104 var key = m[1];
105 var value = m[2];
106 if (flags.bools[key]) {
107 value = value !== 'false';
108 }
109 setArg(key, value, arg);
110 }
111 else if (/^--no-.+/.test(arg)) {
112 var key = arg.match(/^--no-(.+)/)[1];
113 setArg(key, false, arg);
114 }
115 else if (/^--.+/.test(arg)) {
116 var key = arg.match(/^--(.+)/)[1];
117 var next = args[i + 1];
118 if (next !== undefined && !/^-/.test(next)
119 && !flags.bools[key]
120 && !flags.allBools
121 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
122 setArg(key, next, arg);
123 i++;
124 }
125 else if (/^(true|false)$/.test(next)) {
126 setArg(key, next === 'true', arg);
127 i++;
128 }
129 else {
130 setArg(key, flags.strings[key] ? '' : true, arg);
131 }
132 }
133 else if (/^-[^-]+/.test(arg)) {
134 var letters = arg.slice(1, -1).split('');
135 var broken = false;
136 for (var j = 0; j < letters.length; j++) {
137 var next = arg.slice(j + 2);
138 if (next === '-') {
139 setArg(letters[j], next, arg);
140 continue;
141 }
142 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
143 setArg(letters[j], next.split('=')[1], arg);
144 broken = true;
145 break;
146 }
147 if (/[A-Za-z]/.test(letters[j])
148 && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
149 setArg(letters[j], next, arg);
150 broken = true;
151 break;
152 }
153 if (letters[j + 1] && letters[j + 1].match(/\W/)) {
154 setArg(letters[j], arg.slice(j + 2), arg);
155 broken = true;
156 break;
157 }
158 else {
159 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
160 }
161 }
162 var key = arg.slice(-1)[0];
163 if (!broken && key !== '-') {
164 if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1])
165 && !flags.bools[key]
166 && (aliases[key] ? !aliasIsBoolean(key) : true)) {
167 setArg(key, args[i + 1], arg);
168 i++;
169 }
170 else if (args[i + 1] && /true|false/.test(args[i + 1])) {
171 setArg(key, args[i + 1] === 'true', arg);
172 i++;
173 }
174 else {
175 setArg(key, flags.strings[key] ? '' : true, arg);
176 }
177 }
178 }
179 else {
180 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
181 argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
182 }
183 if (opts.stopEarly) {
184 argv._.push.apply(argv._, args.slice(i + 1));
185 break;
186 }
187 }
188 }
189 Object.keys(defaults).forEach(function (key) {
190 if (!hasKey(argv, key.split('.'))) {
191 setKey(argv, key.split('.'), defaults[key]);
192 (aliases[key] || []).forEach(function (x) {
193 setKey(argv, x.split('.'), defaults[key]);
194 });
195 }
196 });
197 if (opts['--']) {
198 argv['--'] = new Array();
199 notFlags.forEach(function (key) {
200 argv['--'].push(key);
201 });
202 }
203 else {
204 notFlags.forEach(function (key) {
205 argv._.push(key);
206 });
207 }
208 return argv;
209};
210function hasKey(obj, keys) {
211 var o = obj;
212 keys.slice(0, -1).forEach(function (key) {
213 o = (o[key] || {});
214 });
215 var key = keys[keys.length - 1];
216 return key in o;
217}
218function isNumber(x) {
219 if (typeof x === 'number')
220 return true;
221 if (/^0x[0-9a-f]+$/i.test(x))
222 return true;
223 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
224}
225
226var version = "1.12.1";
227
228const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined
229 ? command[name]
230 : config[name] !== undefined
231 ? config[name]
232 : defaultValue;
233const normalizeObjectOptionValue = (optionValue) => {
234 if (!optionValue) {
235 return optionValue;
236 }
237 if (typeof optionValue !== 'object') {
238 return {};
239 }
240 return optionValue;
241};
242const getObjectOption = (config, command, name) => {
243 const commandOption = normalizeObjectOptionValue(command[name]);
244 const configOption = normalizeObjectOptionValue(config[name]);
245 if (commandOption !== undefined) {
246 return commandOption && configOption ? Object.assign({}, configOption, commandOption) : commandOption;
247 }
248 return configOption;
249};
250const defaultOnWarn = warning => {
251 if (typeof warning === 'string') {
252 console.warn(warning);
253 }
254 else {
255 console.warn(warning.message);
256 }
257};
258const getOnWarn = (config, command, defaultOnWarnHandler = defaultOnWarn) => command.silent
259 ? () => { }
260 : config.onwarn
261 ? warning => config.onwarn(warning, defaultOnWarnHandler)
262 : defaultOnWarnHandler;
263const getExternal = (config, command) => {
264 const configExternal = config.external;
265 return typeof configExternal === 'function'
266 ? (id, ...rest) => configExternal(id, ...rest) || command.external.indexOf(id) !== -1
267 : (configExternal || []).concat(command.external);
268};
269const commandAliases = {
270 c: 'config',
271 d: 'dir',
272 e: 'external',
273 f: 'format',
274 g: 'globals',
275 h: 'help',
276 i: 'input',
277 m: 'sourcemap',
278 n: 'name',
279 o: 'file',
280 v: 'version',
281 w: 'watch'
282};
283function mergeOptions({ config = {}, command: rawCommandOptions = {}, defaultOnWarnHandler }) {
284 const command = getCommandOptions(rawCommandOptions);
285 const inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
286 if (command.output) {
287 Object.assign(command, command.output);
288 }
289 const output = config.output;
290 const normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
291 if (normalizedOutputOptions.length === 0)
292 normalizedOutputOptions.push({});
293 const outputOptions = normalizedOutputOptions.map(singleOutputOptions => getOutputOptions(singleOutputOptions, command));
294 const unknownOptionErrors = [];
295 const validInputOptions = Object.keys(inputOptions);
296 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
297 const validOutputOptions = Object.keys(outputOptions[0]);
298 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option');
299 const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform');
300 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
301 return {
302 inputOptions,
303 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
304 outputOptions
305 };
306}
307function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) {
308 const unknownOptions = options.filter(key => validOptions.indexOf(key) === -1 && !ignoredKeys.test(key));
309 if (unknownOptions.length > 0)
310 errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.sort().join(', ')}`);
311}
312function getCommandOptions(rawCommandOptions) {
313 const command = Object.assign({}, rawCommandOptions);
314 command.external = rawCommandOptions.external ? rawCommandOptions.external.split(',') : [];
315 if (rawCommandOptions.globals) {
316 command.globals = Object.create(null);
317 rawCommandOptions.globals.split(',').forEach((str) => {
318 const names = str.split(':');
319 command.globals[names[0]] = names[1];
320 // Add missing Module IDs to external.
321 if (command.external.indexOf(names[0]) === -1) {
322 command.external.push(names[0]);
323 }
324 });
325 }
326 return command;
327}
328function getInputOptions(config, command = {}, defaultOnWarnHandler) {
329 const getOption = createGetOption(config, command);
330 const inputOptions = {
331 acorn: config.acorn,
332 acornInjectPlugins: config.acornInjectPlugins,
333 cache: getOption('cache'),
334 chunkGroupingSize: getOption('chunkGroupingSize', 5000),
335 context: config.context,
336 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
337 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
338 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
339 external: getExternal(config, command),
340 inlineDynamicImports: getOption('inlineDynamicImports', false),
341 input: getOption('input', []),
342 manualChunks: getOption('manualChunks'),
343 moduleContext: config.moduleContext,
344 onwarn: getOnWarn(config, command, defaultOnWarnHandler),
345 perf: getOption('perf', false),
346 plugins: config.plugins,
347 preserveModules: getOption('preserveModules'),
348 preserveSymlinks: getOption('preserveSymlinks'),
349 shimMissingExports: getOption('shimMissingExports'),
350 treeshake: getObjectOption(config, command, 'treeshake'),
351 watch: config.watch
352 };
353 // support rollup({ cache: prevBuildObject })
354 if (inputOptions.cache && inputOptions.cache.cache)
355 inputOptions.cache = inputOptions.cache.cache;
356 return inputOptions;
357}
358function getOutputOptions(config, command = {}) {
359 const getOption = createGetOption(config, command);
360 let format = getOption('format');
361 // Handle format aliases
362 switch (format) {
363 case 'esm':
364 case 'module':
365 format = 'es';
366 break;
367 case 'commonjs':
368 format = 'cjs';
369 }
370 return {
371 amd: Object.assign({}, config.amd, command.amd),
372 assetFileNames: getOption('assetFileNames'),
373 banner: getOption('banner'),
374 chunkFileNames: getOption('chunkFileNames'),
375 compact: getOption('compact', false),
376 dir: getOption('dir'),
377 dynamicImportFunction: getOption('dynamicImportFunction'),
378 entryFileNames: getOption('entryFileNames'),
379 esModule: getOption('esModule', true),
380 exports: getOption('exports'),
381 extend: getOption('extend'),
382 file: getOption('file'),
383 footer: getOption('footer'),
384 format: format === 'esm' ? 'es' : format,
385 freeze: getOption('freeze', true),
386 globals: getOption('globals'),
387 indent: getOption('indent', true),
388 interop: getOption('interop', true),
389 intro: getOption('intro'),
390 name: getOption('name'),
391 namespaceToStringTag: getOption('namespaceToStringTag', false),
392 noConflict: getOption('noConflict'),
393 outro: getOption('outro'),
394 paths: getOption('paths'),
395 preferConst: getOption('preferConst'),
396 sourcemap: getOption('sourcemap'),
397 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
398 sourcemapFile: getOption('sourcemapFile'),
399 sourcemapPathTransform: getOption('sourcemapPathTransform'),
400 strict: getOption('strict', true)
401 };
402}
403
404var modules = {};
405var getModule = function (dir) {
406 var rootPath = dir ? path__default.resolve(dir) : process.cwd();
407 var rootName = path__default.join(rootPath, '@root');
408 var root = modules[rootName];
409 if (!root) {
410 root = new module$1(rootName);
411 root.filename = rootName;
412 root.paths = module$1._nodeModulePaths(rootPath);
413 modules[rootName] = root;
414 }
415 return root;
416};
417var requireRelative = function (requested, relativeTo) {
418 var root = getModule(relativeTo);
419 return root.require(requested);
420};
421requireRelative.resolve = function (requested, relativeTo) {
422 var root = getModule(relativeTo);
423 return module$1._resolveFilename(requested, root);
424};
425var requireRelative_1 = requireRelative;
426
427const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
428function isAbsolute(path) {
429 return absolutePath.test(path);
430}
431
432function getAliasName(id) {
433 const base = path.basename(id);
434 return base.substr(0, base.length - path.extname(id).length);
435}
436function relativeId(id) {
437 if (typeof process === 'undefined' || !isAbsolute(id))
438 return id;
439 return path.relative(process.cwd(), id);
440}
441
442const tc = {
443 enabled: process.env.FORCE_COLOR ||
444 process.platform === "win32" ||
445 (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")
446};
447const Styles = (tc.Styles = {});
448const defineProp = Object.defineProperty;
449const init = (style, open, close, re) => {
450 let i, len = 1, seq = [(Styles[style] = { open, close, re })];
451 const fn = s => {
452 if (tc.enabled) {
453 for (i = 0, s += ""; i < len; i++) {
454 style = seq[i];
455 s =
456 (open = style.open) +
457 (~s.indexOf((close = style.close), 4) // skip first \x1b[
458 ? s.replace(style.re, open)
459 : s) +
460 close;
461 }
462 len = 1;
463 }
464 return s;
465 };
466 defineProp(tc, style, {
467 get: () => {
468 for (let k in Styles)
469 defineProp(fn, k, {
470 get: () => ((seq[len++] = Styles[k]), fn)
471 });
472 delete tc[style];
473 return (tc[style] = fn);
474 },
475 configurable: true
476 });
477};
478init("reset", "\x1b[0m", "\x1b[0m", /\x1b\[0m/g);
479init("bold", "\x1b[1m", "\x1b[22m", /\x1b\[22m/g);
480init("dim", "\x1b[2m", "\x1b[22m", /\x1b\[22m/g);
481init("italic", "\x1b[3m", "\x1b[23m", /\x1b\[23m/g);
482init("underline", "\x1b[4m", "\x1b[24m", /\x1b\[24m/g);
483init("inverse", "\x1b[7m", "\x1b[27m", /\x1b\[27m/g);
484init("hidden", "\x1b[8m", "\x1b[28m", /\x1b\[28m/g);
485init("strikethrough", "\x1b[9m", "\x1b[29m", /\x1b\[29m/g);
486init("black", "\x1b[30m", "\x1b[39m", /\x1b\[39m/g);
487init("red", "\x1b[31m", "\x1b[39m", /\x1b\[39m/g);
488init("green", "\x1b[32m", "\x1b[39m", /\x1b\[39m/g);
489init("yellow", "\x1b[33m", "\x1b[39m", /\x1b\[39m/g);
490init("blue", "\x1b[34m", "\x1b[39m", /\x1b\[39m/g);
491init("magenta", "\x1b[35m", "\x1b[39m", /\x1b\[39m/g);
492init("cyan", "\x1b[36m", "\x1b[39m", /\x1b\[39m/g);
493init("white", "\x1b[37m", "\x1b[39m", /\x1b\[39m/g);
494init("gray", "\x1b[90m", "\x1b[39m", /\x1b\[39m/g);
495init("bgBlack", "\x1b[40m", "\x1b[49m", /\x1b\[49m/g);
496init("bgRed", "\x1b[41m", "\x1b[49m", /\x1b\[49m/g);
497init("bgGreen", "\x1b[42m", "\x1b[49m", /\x1b\[49m/g);
498init("bgYellow", "\x1b[43m", "\x1b[49m", /\x1b\[49m/g);
499init("bgBlue", "\x1b[44m", "\x1b[49m", /\x1b\[49m/g);
500init("bgMagenta", "\x1b[45m", "\x1b[49m", /\x1b\[49m/g);
501init("bgCyan", "\x1b[46m", "\x1b[49m", /\x1b\[49m/g);
502init("bgWhite", "\x1b[47m", "\x1b[49m", /\x1b\[49m/g);
503var turbocolor = tc;
504
505// log to stderr to keep `rollup main.js > bundle.js` from breaking
506const stderr = console.error.bind(console);
507function handleError(err, recover = false) {
508 let description = err.message || err;
509 if (err.name)
510 description = `${err.name}: ${description}`;
511 const message = (err.plugin
512 ? `(${err.plugin} plugin) ${description}`
513 : description) || err;
514 stderr(turbocolor.bold.red(`[!] ${turbocolor.bold(message.toString())}`));
515 if (err.url) {
516 stderr(turbocolor.cyan(err.url));
517 }
518 if (err.loc) {
519 stderr(`${relativeId(err.loc.file || err.id)} (${err.loc.line}:${err.loc.column})`);
520 }
521 else if (err.id) {
522 stderr(relativeId(err.id));
523 }
524 if (err.frame) {
525 stderr(turbocolor.dim(err.frame));
526 }
527 if (err.stack) {
528 stderr(turbocolor.dim(err.stack));
529 }
530 stderr('');
531 if (!recover)
532 process.exit(1);
533}
534
535function batchWarnings() {
536 let allWarnings = new Map();
537 let count = 0;
538 return {
539 get count() {
540 return count;
541 },
542 add: (warning) => {
543 if (typeof warning === 'string') {
544 warning = { code: 'UNKNOWN', message: warning };
545 }
546 if (warning.code in immediateHandlers) {
547 immediateHandlers[warning.code](warning);
548 return;
549 }
550 if (!allWarnings.has(warning.code))
551 allWarnings.set(warning.code, []);
552 allWarnings.get(warning.code).push(warning);
553 count += 1;
554 },
555 flush: () => {
556 if (count === 0)
557 return;
558 const codes = Array.from(allWarnings.keys()).sort((a, b) => {
559 if (deferredHandlers[a] && deferredHandlers[b]) {
560 return deferredHandlers[a].priority - deferredHandlers[b].priority;
561 }
562 if (deferredHandlers[a])
563 return -1;
564 if (deferredHandlers[b])
565 return 1;
566 return allWarnings.get(b).length - allWarnings.get(a).length;
567 });
568 codes.forEach(code => {
569 const handler = deferredHandlers[code];
570 const warnings = allWarnings.get(code);
571 if (handler) {
572 handler.fn(warnings);
573 }
574 else {
575 warnings.forEach(warning => {
576 title(warning.message);
577 if (warning.url)
578 info(warning.url);
579 const id = (warning.loc && warning.loc.file) || warning.id;
580 if (id) {
581 const loc = warning.loc
582 ? `${relativeId(id)}: (${warning.loc.line}:${warning.loc.column})`
583 : relativeId(id);
584 stderr(turbocolor.bold(relativeId(loc)));
585 }
586 if (warning.frame)
587 info(warning.frame);
588 });
589 }
590 });
591 allWarnings = new Map();
592 count = 0;
593 }
594 };
595}
596const immediateHandlers = {
597 UNKNOWN_OPTION: warning => {
598 title(`You have passed an unrecognized option`);
599 stderr(warning.message);
600 },
601 MISSING_NODE_BUILTINS: warning => {
602 title(`Missing shims for Node.js built-ins`);
603 const detail = warning.modules.length === 1
604 ? `'${warning.modules[0]}'`
605 : `${warning.modules
606 .slice(0, -1)
607 .map((name) => `'${name}'`)
608 .join(', ')} and '${warning.modules.slice(-1)}'`;
609 stderr(`Creating a browser bundle that depends on ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`);
610 },
611 MIXED_EXPORTS: () => {
612 title('Mixing named and default exports');
613 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`);
614 },
615 EMPTY_BUNDLE: () => {
616 title(`Generated an empty bundle`);
617 }
618};
619// TODO select sensible priorities
620const deferredHandlers = {
621 UNUSED_EXTERNAL_IMPORT: {
622 fn: warnings => {
623 title('Unused external imports');
624 warnings.forEach(warning => {
625 stderr(`${warning.names} imported from external module '${warning.source}' but never used`);
626 });
627 },
628 priority: 1
629 },
630 UNRESOLVED_IMPORT: {
631 fn: warnings => {
632 title('Unresolved dependencies');
633 info('https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency');
634 const dependencies = new Map();
635 warnings.forEach(warning => {
636 if (!dependencies.has(warning.source))
637 dependencies.set(warning.source, []);
638 dependencies.get(warning.source).push(warning.importer);
639 });
640 Array.from(dependencies.keys()).forEach(dependency => {
641 const importers = dependencies.get(dependency);
642 stderr(`${turbocolor.bold(dependency)} (imported by ${importers.join(', ')})`);
643 });
644 },
645 priority: 1
646 },
647 MISSING_EXPORT: {
648 fn: warnings => {
649 title('Missing exports');
650 info('https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-');
651 warnings.forEach(warning => {
652 stderr(turbocolor.bold(warning.importer));
653 stderr(`${warning.missing} is not exported by ${warning.exporter}`);
654 stderr(turbocolor.gray(warning.frame));
655 });
656 },
657 priority: 1
658 },
659 THIS_IS_UNDEFINED: {
660 fn: warnings => {
661 title('`this` has been rewritten to `undefined`');
662 info('https://rollupjs.org/guide/en#error-this-is-undefined');
663 showTruncatedWarnings(warnings);
664 },
665 priority: 1
666 },
667 EVAL: {
668 fn: warnings => {
669 title('Use of eval is strongly discouraged');
670 info('https://rollupjs.org/guide/en#avoiding-eval');
671 showTruncatedWarnings(warnings);
672 },
673 priority: 1
674 },
675 NON_EXISTENT_EXPORT: {
676 fn: warnings => {
677 title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
678 showTruncatedWarnings(warnings);
679 },
680 priority: 1
681 },
682 NAMESPACE_CONFLICT: {
683 fn: warnings => {
684 title(`Conflicting re-exports`);
685 warnings.forEach(warning => {
686 stderr(`${turbocolor.bold(relativeId(warning.reexporter))} re-exports '${warning.name}' from both ${relativeId(warning.sources[0])} and ${relativeId(warning.sources[1])} (will be ignored)`);
687 });
688 },
689 priority: 1
690 },
691 MISSING_GLOBAL_NAME: {
692 fn: warnings => {
693 title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
694 stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
695 warnings.forEach(warning => {
696 stderr(`${turbocolor.bold(warning.source)} (guessing '${warning.guess}')`);
697 });
698 },
699 priority: 1
700 },
701 SOURCEMAP_BROKEN: {
702 fn: warnings => {
703 title(`Broken sourcemap`);
704 info('https://rollupjs.org/guide/en#warning-sourcemap-is-likely-to-be-incorrect');
705 const plugins = Array.from(new Set(warnings.map(w => w.plugin).filter(Boolean)));
706 const detail = plugins.length === 0
707 ? ''
708 : plugins.length > 1
709 ? ` (such as ${plugins
710 .slice(0, -1)
711 .map(p => `'${p}'`)
712 .join(', ')} and '${plugins.slice(-1)}')`
713 : ` (such as '${plugins[0]}')`;
714 stderr(`Plugins that transform code${detail} should generate accompanying sourcemaps`);
715 },
716 priority: 1
717 },
718 PLUGIN_WARNING: {
719 fn: warnings => {
720 const nestedByPlugin = nest(warnings, 'plugin');
721 nestedByPlugin.forEach(({ key: plugin, items }) => {
722 const nestedByMessage = nest(items, 'message');
723 let lastUrl;
724 nestedByMessage.forEach(({ key: message, items }) => {
725 title(`${plugin} plugin: ${message}`);
726 items.forEach(warning => {
727 if (warning.url !== lastUrl)
728 info((lastUrl = warning.url));
729 if (warning.id) {
730 let loc = relativeId(warning.id);
731 if (warning.loc) {
732 loc += `: (${warning.loc.line}:${warning.loc.column})`;
733 }
734 stderr(turbocolor.bold(loc));
735 }
736 if (warning.frame)
737 info(warning.frame);
738 });
739 });
740 });
741 },
742 priority: 1
743 }
744};
745function title(str) {
746 stderr(`${turbocolor.bold.yellow('(!)')} ${turbocolor.bold.yellow(str)}`);
747}
748function info(url) {
749 stderr(turbocolor.gray(url));
750}
751function nest(array, prop) {
752 const nested = [];
753 const lookup = new Map();
754 array.forEach(item => {
755 const key = item[prop];
756 if (!lookup.has(key)) {
757 lookup.set(key, {
758 items: [],
759 key
760 });
761 nested.push(lookup.get(key));
762 }
763 lookup.get(key).items.push(item);
764 });
765 return nested;
766}
767function showTruncatedWarnings(warnings) {
768 const nestedByModule = nest(warnings, 'id');
769 const sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
770 sliced.forEach(({ key: id, items }) => {
771 stderr(turbocolor.bold(relativeId(id)));
772 stderr(turbocolor.gray(items[0].frame));
773 if (items.length > 1) {
774 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
775 }
776 });
777 if (nestedByModule.length > sliced.length) {
778 stderr(`\n...and ${nestedByModule.length - sliced.length} other files`);
779 }
780}
781
782var parseMs = milliseconds => {
783 if (typeof milliseconds !== 'number') {
784 throw new TypeError('Expected a number');
785 }
786 const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil;
787 return {
788 days: roundTowardsZero(milliseconds / 86400000),
789 hours: roundTowardsZero(milliseconds / 3600000) % 24,
790 minutes: roundTowardsZero(milliseconds / 60000) % 60,
791 seconds: roundTowardsZero(milliseconds / 1000) % 60,
792 milliseconds: roundTowardsZero(milliseconds) % 1000,
793 microseconds: roundTowardsZero(milliseconds * 1000) % 1000,
794 nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000
795 };
796};
797
798const pluralize = (word, count) => count === 1 ? word : word + 's';
799var prettyMs = (milliseconds, options = {}) => {
800 if (!Number.isFinite(milliseconds)) {
801 throw new TypeError('Expected a finite number');
802 }
803 if (options.compact) {
804 options.secondsDecimalDigits = 0;
805 options.millisecondsDecimalDigits = 0;
806 }
807 const result = [];
808 const add = (value, long, short, valueString) => {
809 if (value === 0) {
810 return;
811 }
812 const postfix = options.verbose ? ' ' + pluralize(long, value) : short;
813 result.push((valueString || value) + postfix);
814 };
815 const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
816 options.secondsDecimalDigits :
817 1;
818 if (secondsDecimalDigits < 1) {
819 const difference = 1000 - (milliseconds % 1000);
820 if (difference < 500) {
821 milliseconds += difference;
822 }
823 }
824 const parsed = parseMs(milliseconds);
825 add(Math.trunc(parsed.days / 365), 'year', 'y');
826 add(parsed.days % 365, 'day', 'd');
827 add(parsed.hours, 'hour', 'h');
828 add(parsed.minutes, 'minute', 'm');
829 if (options.separateMilliseconds ||
830 options.formatSubMilliseconds ||
831 milliseconds < 1000) {
832 add(parsed.seconds, 'second', 's');
833 if (options.formatSubMilliseconds) {
834 add(parsed.milliseconds, 'millisecond', 'ms');
835 add(parsed.microseconds, 'microsecond', 'µs');
836 add(parsed.nanoseconds, 'nanosecond', 'ns');
837 }
838 else {
839 const millisecondsAndBelow = parsed.milliseconds +
840 (parsed.microseconds / 1000) +
841 (parsed.nanoseconds / 1e6);
842 const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === 'number' ?
843 options.millisecondsDecimalDigits :
844 0;
845 const millisecondsString = millisecondsDecimalDigits ?
846 millisecondsAndBelow.toFixed(millisecondsDecimalDigits) :
847 Math.ceil(millisecondsAndBelow);
848 add(parseFloat(millisecondsString, 10), 'millisecond', 'ms', millisecondsString);
849 }
850 }
851 else {
852 const seconds = (milliseconds / 1000) % 60;
853 const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
854 options.secondsDecimalDigits :
855 1;
856 const secondsFixed = seconds.toFixed(secondsDecimalDigits);
857 const secondsString = options.keepDecimalsOnWholeSeconds ?
858 secondsFixed :
859 secondsFixed.replace(/\.0+$/, '');
860 add(parseFloat(secondsString, 10), 'second', 's', secondsString);
861 }
862 if (result.length === 0) {
863 return '0' + (options.verbose ? ' milliseconds' : 'ms');
864 }
865 if (options.compact) {
866 return '~' + result[0];
867 }
868 if (typeof options.unitCount === 'number') {
869 return '~' + result.slice(0, Math.max(options.unitCount, 1)).join(' ');
870 }
871 return result.join(' ');
872};
873
874let SOURCEMAPPING_URL = 'sourceMa';
875SOURCEMAPPING_URL += 'ppingURL';
876var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
877
878const UNITS = [
879 'B',
880 'kB',
881 'MB',
882 'GB',
883 'TB',
884 'PB',
885 'EB',
886 'ZB',
887 'YB'
888];
889/*
890Formats the given number using `Number#toLocaleString`.
891- If locale is a string, the value is expected to be a locale-key (for example: `de`).
892- If locale is true, the system default locale is used for translation.
893- If no value for locale is specified, the number is returned unmodified.
894*/
895const toLocaleString = (number, locale) => {
896 let result = number;
897 if (typeof locale === 'string') {
898 result = number.toLocaleString(locale);
899 }
900 else if (locale === true) {
901 result = number.toLocaleString();
902 }
903 return result;
904};
905var prettyBytes = (number, options) => {
906 if (!Number.isFinite(number)) {
907 throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
908 }
909 options = Object.assign({}, options);
910 if (options.signed && number === 0) {
911 return ' 0 B';
912 }
913 const isNegative = number < 0;
914 const prefix = isNegative ? '-' : (options.signed ? '+' : '');
915 if (isNegative) {
916 number = -number;
917 }
918 if (number < 1) {
919 const numberString = toLocaleString(number, options.locale);
920 return prefix + numberString + ' B';
921 }
922 const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
923 // eslint-disable-next-line unicorn/prefer-exponentiation-operator
924 number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
925 const numberString = toLocaleString(number, options.locale);
926 const unit = UNITS[exponent];
927 return prefix + numberString + ' ' + unit;
928};
929
930function printTimings(timings) {
931 Object.keys(timings).forEach(label => {
932 const color = label[0] === '#' ? (label[1] !== '#' ? turbocolor.underline : turbocolor.bold) : (text) => text;
933 const [time, memory, total] = timings[label];
934 const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
935 console.info(color(row));
936 });
937}
938
939function build(inputOptions, outputOptions, warnings, silent = false) {
940 const useStdout = !outputOptions[0].file && !outputOptions[0].dir;
941 const start = Date.now();
942 const files = useStdout ? ['stdout'] : outputOptions.map(t => relativeId(t.file || t.dir));
943 if (!silent) {
944 let inputFiles;
945 if (typeof inputOptions.input === 'string') {
946 inputFiles = inputOptions.input;
947 }
948 else if (inputOptions.input instanceof Array) {
949 inputFiles = inputOptions.input.join(', ');
950 }
951 else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
952 inputFiles = Object.keys(inputOptions.input)
953 .map(name => inputOptions.input[name])
954 .join(', ');
955 }
956 stderr(turbocolor.cyan(`\n${turbocolor.bold(inputFiles)} → ${turbocolor.bold(files.join(', '))}...`));
957 }
958 return rollup.rollup(inputOptions)
959 .then((bundle) => {
960 if (useStdout) {
961 const output = outputOptions[0];
962 if (output.sourcemap && output.sourcemap !== 'inline') {
963 handleError({
964 code: 'MISSING_OUTPUT_OPTION',
965 message: 'You must specify a --file (-o) option when creating a file with a sourcemap'
966 });
967 }
968 return bundle.generate(output).then(({ output: outputs }) => {
969 for (const file of outputs) {
970 let source;
971 if (file.isAsset) {
972 source = file.source;
973 }
974 else {
975 source = file.code;
976 if (output.sourcemap === 'inline') {
977 source += `\n//# ${SOURCEMAPPING_URL$1}=${file.map.toUrl()}\n`;
978 }
979 }
980 if (outputs.length > 1)
981 process.stdout.write('\n' + turbocolor.cyan(turbocolor.bold('//→ ' + file.fileName + ':')) + '\n');
982 process.stdout.write(source);
983 }
984 });
985 }
986 return Promise.all(outputOptions.map(output => bundle.write(output))).then(() => bundle);
987 })
988 .then((bundle) => {
989 warnings.flush();
990 if (!silent)
991 stderr(turbocolor.green(`created ${turbocolor.bold(files.join(', '))} in ${turbocolor.bold(prettyMs(Date.now() - start))}`));
992 if (bundle && bundle.getTimings) {
993 printTimings(bundle.getTimings());
994 }
995 })
996 .catch((err) => {
997 if (warnings.count > 0)
998 warnings.flush();
999 handleError(err);
1000 });
1001}
1002
1003function loadConfigFile(configFile, commandOptions = {}) {
1004 const silent = commandOptions.silent || false;
1005 const warnings = batchWarnings();
1006 return rollup__default
1007 .rollup({
1008 external: (id) => (id[0] !== '.' && !path__default.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
1009 input: configFile,
1010 onwarn: warnings.add,
1011 treeshake: false
1012 })
1013 .then((bundle) => {
1014 if (!silent && warnings.count > 0) {
1015 stderr(turbocolor.bold(`loaded ${relativeId(configFile)} with warnings`));
1016 warnings.flush();
1017 }
1018 return bundle.generate({
1019 exports: 'named',
1020 format: 'cjs'
1021 });
1022 })
1023 .then(({ output: [{ code }] }) => {
1024 // temporarily override require
1025 const defaultLoader = require.extensions['.js'];
1026 require.extensions['.js'] = (module, filename) => {
1027 if (filename === configFile) {
1028 module._compile(code, filename);
1029 }
1030 else {
1031 defaultLoader(module, filename);
1032 }
1033 };
1034 delete require.cache[configFile];
1035 return Promise.resolve(require(configFile))
1036 .then(configFileContent => {
1037 if (configFileContent.default)
1038 configFileContent = configFileContent.default;
1039 if (typeof configFileContent === 'function') {
1040 return configFileContent(commandOptions);
1041 }
1042 return configFileContent;
1043 })
1044 .then(configs => {
1045 if (Object.keys(configs).length === 0) {
1046 handleError({
1047 code: 'MISSING_CONFIG',
1048 message: 'Config file must export an options object, or an array of options objects',
1049 url: 'https://rollupjs.org/guide/en#configuration-files'
1050 });
1051 }
1052 require.extensions['.js'] = defaultLoader;
1053 return Array.isArray(configs) ? configs : [configs];
1054 });
1055 });
1056}
1057
1058var timeZone = date => {
1059 const offset = (date || new Date()).getTimezoneOffset();
1060 const absOffset = Math.abs(offset);
1061 const hours = Math.floor(absOffset / 60);
1062 const minutes = absOffset % 60;
1063 const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
1064 return (offset < 0 ? '+' : '-') + hours + minutesOut;
1065};
1066
1067const dateTime = options => {
1068 options = Object.assign({
1069 date: new Date(),
1070 local: true,
1071 showTimeZone: false,
1072 showMilliseconds: false
1073 }, options);
1074 let { date } = options;
1075 if (options.local) {
1076 // Offset the date so it will return the correct value when getting the ISO string
1077 date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
1078 }
1079 let end = '';
1080 if (options.showTimeZone) {
1081 end = ' UTC' + (options.local ? timeZone(date) : '');
1082 }
1083 if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {
1084 end = ` ${date.getUTCMilliseconds()}ms${end}`;
1085 }
1086 return date
1087 .toISOString()
1088 .replace(/T/, ' ')
1089 .replace(/\..+/, end);
1090};
1091var dateTime_1 = dateTime;
1092// TODO: Remove this for the next major release
1093var default_1 = dateTime;
1094dateTime_1.default = default_1;
1095
1096function createCommonjsModule(fn, module) {
1097 return module = { exports: {} }, fn(module, module.exports), module.exports;
1098}
1099
1100var signals = createCommonjsModule(function (module) {
1101 // This is not the set of all possible signals.
1102 //
1103 // It IS, however, the set of all signals that trigger
1104 // an exit on either Linux or BSD systems. Linux is a
1105 // superset of the signal names supported on BSD, and
1106 // the unknown signals just fail to register, so we can
1107 // catch that easily enough.
1108 //
1109 // Don't bother with SIGKILL. It's uncatchable, which
1110 // means that we can't fire any callbacks anyway.
1111 //
1112 // If a user does happen to register a handler on a non-
1113 // fatal signal like SIGWINCH or something, and then
1114 // exit, it'll end up firing `process.emit('exit')`, so
1115 // the handler will be fired anyway.
1116 //
1117 // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
1118 // artificially, inherently leave the process in a
1119 // state from which it is not safe to try and enter JS
1120 // listeners.
1121 module.exports = [
1122 'SIGABRT',
1123 'SIGALRM',
1124 'SIGHUP',
1125 'SIGINT',
1126 'SIGTERM'
1127 ];
1128 if (process.platform !== 'win32') {
1129 module.exports.push('SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
1130 // should detect profiler and enable/disable accordingly.
1131 // see #21
1132 // 'SIGPROF'
1133 );
1134 }
1135 if (process.platform === 'linux') {
1136 module.exports.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED');
1137 }
1138});
1139
1140// Note: since nyc uses this module to output coverage, any lines
1141// that are in the direct sync flow of nyc's outputCoverage are
1142// ignored, since we can never get coverage for them.
1143var signals$1 = signals;
1144var EE = events;
1145/* istanbul ignore if */
1146if (typeof EE !== 'function') {
1147 EE = EE.EventEmitter;
1148}
1149var emitter;
1150if (process.__signal_exit_emitter__) {
1151 emitter = process.__signal_exit_emitter__;
1152}
1153else {
1154 emitter = process.__signal_exit_emitter__ = new EE();
1155 emitter.count = 0;
1156 emitter.emitted = {};
1157}
1158// Because this emitter is a global, we have to check to see if a
1159// previous version of this library failed to enable infinite listeners.
1160// I know what you're about to say. But literally everything about
1161// signal-exit is a compromise with evil. Get used to it.
1162if (!emitter.infinite) {
1163 emitter.setMaxListeners(Infinity);
1164 emitter.infinite = true;
1165}
1166var signalExit = function (cb, opts) {
1167 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
1168 if (loaded === false) {
1169 load();
1170 }
1171 var ev = 'exit';
1172 if (opts && opts.alwaysLast) {
1173 ev = 'afterexit';
1174 }
1175 var remove = function () {
1176 emitter.removeListener(ev, cb);
1177 if (emitter.listeners('exit').length === 0 &&
1178 emitter.listeners('afterexit').length === 0) {
1179 unload();
1180 }
1181 };
1182 emitter.on(ev, cb);
1183 return remove;
1184};
1185var unload_1 = unload;
1186function unload() {
1187 if (!loaded) {
1188 return;
1189 }
1190 loaded = false;
1191 signals$1.forEach(function (sig) {
1192 try {
1193 process.removeListener(sig, sigListeners[sig]);
1194 }
1195 catch (er) { }
1196 });
1197 process.emit = originalProcessEmit;
1198 process.reallyExit = originalProcessReallyExit;
1199 emitter.count -= 1;
1200}
1201function emit(event, code, signal) {
1202 if (emitter.emitted[event]) {
1203 return;
1204 }
1205 emitter.emitted[event] = true;
1206 emitter.emit(event, code, signal);
1207}
1208// { <signal>: <listener fn>, ... }
1209var sigListeners = {};
1210signals$1.forEach(function (sig) {
1211 sigListeners[sig] = function listener() {
1212 // If there are no other listeners, an exit is coming!
1213 // Simplest way: remove us and then re-send the signal.
1214 // We know that this will kill the process, so we can
1215 // safely emit now.
1216 var listeners = process.listeners(sig);
1217 if (listeners.length === emitter.count) {
1218 unload();
1219 emit('exit', null, sig);
1220 /* istanbul ignore next */
1221 emit('afterexit', null, sig);
1222 /* istanbul ignore next */
1223 process.kill(process.pid, sig);
1224 }
1225 };
1226});
1227var signals_1 = function () {
1228 return signals$1;
1229};
1230var load_1 = load;
1231var loaded = false;
1232function load() {
1233 if (loaded) {
1234 return;
1235 }
1236 loaded = true;
1237 // This is the number of onSignalExit's that are in play.
1238 // It's important so that we can count the correct number of
1239 // listeners on signals, and don't wait for the other one to
1240 // handle it instead of us.
1241 emitter.count += 1;
1242 signals$1 = signals$1.filter(function (sig) {
1243 try {
1244 process.on(sig, sigListeners[sig]);
1245 return true;
1246 }
1247 catch (er) {
1248 return false;
1249 }
1250 });
1251 process.emit = processEmit;
1252 process.reallyExit = processReallyExit;
1253}
1254var originalProcessReallyExit = process.reallyExit;
1255function processReallyExit(code) {
1256 process.exitCode = code || 0;
1257 emit('exit', process.exitCode, null);
1258 /* istanbul ignore next */
1259 emit('afterexit', process.exitCode, null);
1260 /* istanbul ignore next */
1261 originalProcessReallyExit.call(process, process.exitCode);
1262}
1263var originalProcessEmit = process.emit;
1264function processEmit(ev, arg) {
1265 if (ev === 'exit') {
1266 if (arg !== undefined) {
1267 process.exitCode = arg;
1268 }
1269 var ret = originalProcessEmit.apply(this, arguments);
1270 emit('exit', process.exitCode, null);
1271 /* istanbul ignore next */
1272 emit('afterexit', process.exitCode, null);
1273 return ret;
1274 }
1275 else {
1276 return originalProcessEmit.apply(this, arguments);
1277 }
1278}
1279signalExit.unload = unload_1;
1280signalExit.signals = signals_1;
1281signalExit.load = load_1;
1282
1283var ansiEscapes_1 = createCommonjsModule(function (module) {
1284 const ansiEscapes = module.exports;
1285 // TODO: remove this in the next major version
1286 module.exports.default = ansiEscapes;
1287 const ESC = '\u001B[';
1288 const OSC = '\u001B]';
1289 const BEL = '\u0007';
1290 const SEP = ';';
1291 const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
1292 ansiEscapes.cursorTo = (x, y) => {
1293 if (typeof x !== 'number') {
1294 throw new TypeError('The `x` argument is required');
1295 }
1296 if (typeof y !== 'number') {
1297 return ESC + (x + 1) + 'G';
1298 }
1299 return ESC + (y + 1) + ';' + (x + 1) + 'H';
1300 };
1301 ansiEscapes.cursorMove = (x, y) => {
1302 if (typeof x !== 'number') {
1303 throw new TypeError('The `x` argument is required');
1304 }
1305 let ret = '';
1306 if (x < 0) {
1307 ret += ESC + (-x) + 'D';
1308 }
1309 else if (x > 0) {
1310 ret += ESC + x + 'C';
1311 }
1312 if (y < 0) {
1313 ret += ESC + (-y) + 'A';
1314 }
1315 else if (y > 0) {
1316 ret += ESC + y + 'B';
1317 }
1318 return ret;
1319 };
1320 ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
1321 ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
1322 ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
1323 ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
1324 ansiEscapes.cursorLeft = ESC + 'G';
1325 ansiEscapes.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');
1326 ansiEscapes.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');
1327 ansiEscapes.cursorGetPosition = ESC + '6n';
1328 ansiEscapes.cursorNextLine = ESC + 'E';
1329 ansiEscapes.cursorPrevLine = ESC + 'F';
1330 ansiEscapes.cursorHide = ESC + '?25l';
1331 ansiEscapes.cursorShow = ESC + '?25h';
1332 ansiEscapes.eraseLines = count => {
1333 let clear = '';
1334 for (let i = 0; i < count; i++) {
1335 clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
1336 }
1337 if (count) {
1338 clear += ansiEscapes.cursorLeft;
1339 }
1340 return clear;
1341 };
1342 ansiEscapes.eraseEndLine = ESC + 'K';
1343 ansiEscapes.eraseStartLine = ESC + '1K';
1344 ansiEscapes.eraseLine = ESC + '2K';
1345 ansiEscapes.eraseDown = ESC + 'J';
1346 ansiEscapes.eraseUp = ESC + '1J';
1347 ansiEscapes.eraseScreen = ESC + '2J';
1348 ansiEscapes.scrollUp = ESC + 'S';
1349 ansiEscapes.scrollDown = ESC + 'T';
1350 ansiEscapes.clearScreen = '\u001Bc';
1351 ansiEscapes.clearTerminal = process.platform === 'win32' ?
1352 `${ansiEscapes.eraseScreen}${ESC}0f` :
1353 // 1. Erases the screen (Only done in case `2` is not supported)
1354 // 2. Erases the whole screen including scrollback buffer
1355 // 3. Moves cursor to the top-left position
1356 // More info: https://www.real-world-systems.com/docs/ANSIcode.html
1357 `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
1358 ansiEscapes.beep = BEL;
1359 ansiEscapes.link = (text, url) => {
1360 return [
1361 OSC,
1362 '8',
1363 SEP,
1364 SEP,
1365 url,
1366 BEL,
1367 text,
1368 OSC,
1369 '8',
1370 SEP,
1371 SEP,
1372 BEL
1373 ].join('');
1374 };
1375 ansiEscapes.image = (buffer, options = {}) => {
1376 let ret = `${OSC}1337;File=inline=1`;
1377 if (options.width) {
1378 ret += `;width=${options.width}`;
1379 }
1380 if (options.height) {
1381 ret += `;height=${options.height}`;
1382 }
1383 if (options.preserveAspectRatio === false) {
1384 ret += ';preserveAspectRatio=0';
1385 }
1386 return ret + ':' + buffer.toString('base64') + BEL;
1387 };
1388 ansiEscapes.iTerm = {
1389 setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`
1390 };
1391});
1392
1393const SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';
1394const HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';
1395const isWindows = process.platform === 'win32';
1396const isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);
1397const isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';
1398const supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;
1399function alternateScreen(enabled) {
1400 if (!enabled) {
1401 let needAnnounce = true;
1402 return {
1403 open() { },
1404 close() { },
1405 reset(heading) {
1406 if (needAnnounce) {
1407 stderr(heading);
1408 needAnnounce = false;
1409 }
1410 }
1411 };
1412 }
1413 return {
1414 open() {
1415 if (supportsAnsi) {
1416 process.stderr.write(SHOW_ALTERNATE_SCREEN);
1417 }
1418 },
1419 close() {
1420 if (supportsAnsi) {
1421 process.stderr.write(HIDE_ALTERNATE_SCREEN);
1422 }
1423 },
1424 reset(heading) {
1425 stderr(`${ansiEscapes_1.eraseScreen}${ansiEscapes_1.cursorTo(0, 0)}${heading}`);
1426 }
1427 };
1428}
1429
1430function watch(configFile, configs, command, silent = false) {
1431 const isTTY = Boolean(process.stderr.isTTY);
1432 const warnings = batchWarnings();
1433 const initialConfigs = processConfigs(configs);
1434 const clearScreen = initialConfigs.every(config => config.watch.clearScreen !== false);
1435 const screen = alternateScreen(isTTY && clearScreen);
1436 screen.open();
1437 let watcher;
1438 let configWatcher;
1439 let processConfigsErr;
1440 function processConfigs(configs) {
1441 return configs.map(options => {
1442 const merged = mergeOptions({
1443 command,
1444 config: options,
1445 defaultOnWarnHandler: warnings.add
1446 });
1447 const result = Object.assign({}, merged.inputOptions, { output: merged.outputOptions });
1448 if (!result.watch)
1449 result.watch = {};
1450 if (merged.optionError)
1451 merged.inputOptions.onwarn({
1452 code: 'UNKNOWN_OPTION',
1453 message: merged.optionError
1454 });
1455 if (merged.inputOptions.watch &&
1456 merged.inputOptions.watch.clearScreen === false) {
1457 processConfigsErr = stderr;
1458 }
1459 return result;
1460 });
1461 }
1462 function start(configs) {
1463 const screenWriter = processConfigsErr || screen.reset;
1464 watcher = rollup.watch(configs);
1465 watcher.on('event', (event) => {
1466 switch (event.code) {
1467 case 'FATAL':
1468 screen.close();
1469 handleError(event.error, true);
1470 process.exit(1);
1471 break;
1472 case 'ERROR':
1473 warnings.flush();
1474 handleError(event.error, true);
1475 break;
1476 case 'START':
1477 if (!silent) {
1478 screenWriter(turbocolor.underline(`rollup v${rollup.VERSION}`));
1479 }
1480 break;
1481 case 'BUNDLE_START':
1482 if (!silent) {
1483 let input = event.input;
1484 if (typeof input !== 'string') {
1485 input = Array.isArray(input)
1486 ? input.join(', ')
1487 : Object.keys(input)
1488 .map(key => input[key])
1489 .join(', ');
1490 }
1491 stderr(turbocolor.cyan(`bundles ${turbocolor.bold(input)} → ${turbocolor.bold(event.output.map(relativeId).join(', '))}...`));
1492 }
1493 break;
1494 case 'BUNDLE_END':
1495 warnings.flush();
1496 if (!silent)
1497 stderr(turbocolor.green(`created ${turbocolor.bold(event.output.map(relativeId).join(', '))} in ${turbocolor.bold(prettyMs(event.duration))}`));
1498 if (event.result && event.result.getTimings) {
1499 printTimings(event.result.getTimings());
1500 }
1501 break;
1502 case 'END':
1503 if (!silent && isTTY) {
1504 stderr(`\n[${dateTime_1()}] waiting for changes...`);
1505 }
1506 }
1507 });
1508 }
1509 // catch ctrl+c, kill, and uncaught errors
1510 const removeOnExit = signalExit(close);
1511 process.on('uncaughtException', close);
1512 // only listen to stdin if it is a pipe
1513 if (!process.stdin.isTTY) {
1514 process.stdin.on('end', close); // in case we ever support stdin!
1515 }
1516 function close(err) {
1517 removeOnExit();
1518 process.removeListener('uncaughtException', close);
1519 // removing a non-existent listener is a no-op
1520 process.stdin.removeListener('end', close);
1521 screen.close();
1522 if (watcher)
1523 watcher.close();
1524 if (configWatcher)
1525 configWatcher.close();
1526 if (err) {
1527 console.error(err);
1528 process.exit(1);
1529 }
1530 }
1531 try {
1532 start(initialConfigs);
1533 }
1534 catch (err) {
1535 close(err);
1536 return;
1537 }
1538 if (configFile && !configFile.startsWith('node:')) {
1539 let restarting = false;
1540 let aborted = false;
1541 let configFileData = fs__default.readFileSync(configFile, 'utf-8');
1542 const restart = () => {
1543 const newConfigFileData = fs__default.readFileSync(configFile, 'utf-8');
1544 if (newConfigFileData === configFileData)
1545 return;
1546 configFileData = newConfigFileData;
1547 if (restarting) {
1548 aborted = true;
1549 return;
1550 }
1551 restarting = true;
1552 loadConfigFile(configFile, command)
1553 .then((_configs) => {
1554 restarting = false;
1555 if (aborted) {
1556 aborted = false;
1557 restart();
1558 }
1559 else {
1560 watcher.close();
1561 start(initialConfigs);
1562 }
1563 })
1564 .catch((err) => {
1565 handleError(err, true);
1566 });
1567 };
1568 configWatcher = fs__default.watch(configFile, (event) => {
1569 if (event === 'change')
1570 restart();
1571 });
1572 }
1573}
1574
1575function runRollup(command) {
1576 let inputSource;
1577 if (command._.length > 0) {
1578 if (command.input) {
1579 handleError({
1580 code: 'DUPLICATE_IMPORT_OPTIONS',
1581 message: 'use --input, or pass input path as argument'
1582 });
1583 }
1584 inputSource = command._;
1585 }
1586 else if (typeof command.input === 'string') {
1587 inputSource = [command.input];
1588 }
1589 else {
1590 inputSource = command.input;
1591 }
1592 if (inputSource && inputSource.length > 0) {
1593 if (inputSource.some((input) => input.indexOf('=') !== -1)) {
1594 command.input = {};
1595 inputSource.forEach((input) => {
1596 const equalsIndex = input.indexOf('=');
1597 const value = input.substr(equalsIndex + 1);
1598 let key = input.substr(0, equalsIndex);
1599 if (!key)
1600 key = getAliasName(input);
1601 command.input[key] = value;
1602 });
1603 }
1604 else {
1605 command.input = inputSource;
1606 }
1607 }
1608 if (command.environment) {
1609 const environment = Array.isArray(command.environment)
1610 ? command.environment
1611 : [command.environment];
1612 environment.forEach((arg) => {
1613 arg.split(',').forEach((pair) => {
1614 const [key, value] = pair.split(':');
1615 if (value) {
1616 process.env[key] = value;
1617 }
1618 else {
1619 process.env[key] = String(true);
1620 }
1621 });
1622 });
1623 }
1624 let configFile = command.config === true ? 'rollup.config.js' : command.config;
1625 if (configFile) {
1626 if (configFile.slice(0, 5) === 'node:') {
1627 const pkgName = configFile.slice(5);
1628 try {
1629 configFile = requireRelative_1.resolve(`rollup-config-${pkgName}`, process.cwd());
1630 }
1631 catch (err) {
1632 try {
1633 configFile = requireRelative_1.resolve(pkgName, process.cwd());
1634 }
1635 catch (err) {
1636 if (err.code === 'MODULE_NOT_FOUND') {
1637 handleError({
1638 code: 'MISSING_EXTERNAL_CONFIG',
1639 message: `Could not resolve config file ${configFile}`
1640 });
1641 }
1642 throw err;
1643 }
1644 }
1645 }
1646 else {
1647 // find real path of config so it matches what Node provides to callbacks in require.extensions
1648 configFile = fs.realpathSync(configFile);
1649 }
1650 if (command.watch)
1651 process.env.ROLLUP_WATCH = 'true';
1652 loadConfigFile(configFile, command)
1653 .then(configs => execute(configFile, configs, command))
1654 .catch(handleError);
1655 }
1656 else {
1657 return execute(configFile, [{ input: null }], command);
1658 }
1659}
1660function execute(configFile, configs, command) {
1661 if (command.watch) {
1662 watch(configFile, configs, command, command.silent);
1663 }
1664 else {
1665 let promise = Promise.resolve();
1666 for (const config of configs) {
1667 promise = promise.then(() => {
1668 const warnings = batchWarnings();
1669 const { inputOptions, outputOptions, optionError } = mergeOptions({
1670 command,
1671 config,
1672 defaultOnWarnHandler: warnings.add
1673 });
1674 if (optionError)
1675 inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });
1676 return build(inputOptions, outputOptions, warnings, command.silent);
1677 });
1678 }
1679 return promise;
1680 }
1681}
1682
1683const command = minimist(process.argv.slice(2), {
1684 alias: commandAliases
1685});
1686if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {
1687 console.log(`\n${help.replace('__VERSION__', version)}\n`);
1688}
1689else if (command.version) {
1690 console.log(`rollup v${version}`);
1691}
1692else {
1693 try {
1694 require('source-map-support').install();
1695 }
1696 catch (err) {
1697 // do nothing
1698 }
1699 runRollup(command);
1700}