UNPKG

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