UNPKG

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