rollup 2.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1783 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ @license
5
+ Rollup.js v2.57.0
6
+ Wed, 22 Sep 2021 04:43:07 GMT - commit b67ef301e8e44f9e0d9b144c0cce441e2a41c3da
7
+
8
+
9
+ https://github.com/rollup/rollup
10
+
11
+ Released under the MIT License.
12
+ */
13
+ 'use strict';
14
+
15
+ Object.defineProperty(exports, '__esModule', { value: true });
16
+
17
+ var rollup = require('../shared/rollup.js');
18
+ var require$$2 = require('util');
19
+ var fs = require('fs');
20
+ var path$1 = require('path');
21
+ var mergeOptions = require('../shared/mergeOptions.js');
22
+ var loadConfigFile_js = require('../shared/loadConfigFile.js');
23
+ var require$$1 = require('module');
24
+ require('crypto');
25
+ require('events');
26
+ require('url');
27
+ require('tty');
28
+
29
+ function _interopNamespaceDefault(e) {
30
+ var n = Object.create(null);
31
+ if (e) {
32
+ for (var k in e) {
33
+ n[k] = e[k];
34
+ }
35
+ }
36
+ n["default"] = e;
37
+ return n;
38
+ }
39
+
40
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path$1);
41
+
42
+ var 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, es, iife, umd, system)\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-p, --plugin <plugin> Use the plugin specified (may be repeated)\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.autoId Generate the AMD ID based off the chunk name\n--amd.basePath <prefix> Path to prepend to auto generated AMD ID\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--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--no-externalLiveBindings Do not generate code to support live bindings\n--failAfterWarnings Exit with an error if the build produced warnings\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--no-freeze Do not freeze namespace objects\n--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks\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--minifyInternalExports Force or disable minification of internal exports\n--namespaceToStringTag Create proper `.toString` methods for namespaces\n--noConflict Generate a noConflict method for UMD globals\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--preferConst Use `const` instead of `var` for exports\n--no-preserveEntrySignatures Avoid facade chunks for entry points\n--preserveModules Preserve module structure\n--preserveModulesRoot Put preserved modules under this path at root level\n--preserveSymlinks Do not follow symlinks when resolving files\n--no-sanitizeFileName Do not replace invalid characters in file names\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--stdin=ext Specify file extension used for stdin input\n--no-stdin Do not read \"-\" from stdin\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--strictDeprecations Throw errors for deprecated features\n--systemNullSetters Replace empty SystemJS setters with `null`\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--no-treeshake.moduleSideEffects Assume modules have no side-effects\n--no-treeshake.propertyReadSideEffects Ignore property access side-effects\n--no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking\n--no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw\n--waitForBundleInput Wait for bundle input files\n--watch.buildDelay <number> Throttle watch rebuilds\n--no-watch.clearScreen Do not clear the screen when rebuilding\n--watch.skipWrite Do not write files to disk when watching\n--watch.exclude <files> Exclude files from being watched\n--watch.include <files> Limit watching to specified files\n--validate Validate output\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";
43
+
44
+ /**
45
+ * @license
46
+ * Copyright (c) 2016, Contributors
47
+ * SPDX-License-Identifier: ISC
48
+ */
49
+ function camelCase(str) {
50
+ // Handle the case where an argument is provided as camel case, e.g., fooBar.
51
+ // by ensuring that the string isn't already mixed case:
52
+ const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
53
+ if (!isCamelCase) {
54
+ str = str.toLowerCase();
55
+ }
56
+ if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
57
+ return str;
58
+ }
59
+ else {
60
+ let camelcase = '';
61
+ let nextChrUpper = false;
62
+ const leadingHyphens = str.match(/^-+/);
63
+ for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
64
+ let chr = str.charAt(i);
65
+ if (nextChrUpper) {
66
+ nextChrUpper = false;
67
+ chr = chr.toUpperCase();
68
+ }
69
+ if (i !== 0 && (chr === '-' || chr === '_')) {
70
+ nextChrUpper = true;
71
+ }
72
+ else if (chr !== '-' && chr !== '_') {
73
+ camelcase += chr;
74
+ }
75
+ }
76
+ return camelcase;
77
+ }
78
+ }
79
+ function decamelize(str, joinString) {
80
+ const lowercase = str.toLowerCase();
81
+ joinString = joinString || '-';
82
+ let notCamelcase = '';
83
+ for (let i = 0; i < str.length; i++) {
84
+ const chrLower = lowercase.charAt(i);
85
+ const chrString = str.charAt(i);
86
+ if (chrLower !== chrString && i > 0) {
87
+ notCamelcase += `${joinString}${lowercase.charAt(i)}`;
88
+ }
89
+ else {
90
+ notCamelcase += chrString;
91
+ }
92
+ }
93
+ return notCamelcase;
94
+ }
95
+ function looksLikeNumber(x) {
96
+ if (x === null || x === undefined)
97
+ return false;
98
+ // if loaded from config, may already be a number.
99
+ if (typeof x === 'number')
100
+ return true;
101
+ // hexadecimal.
102
+ if (/^0x[0-9a-f]+$/i.test(x))
103
+ return true;
104
+ // don't treat 0123 as a number; as it drops the leading '0'.
105
+ if (/^0[^.]/.test(x))
106
+ return false;
107
+ return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
108
+ }
109
+
110
+ /**
111
+ * @license
112
+ * Copyright (c) 2016, Contributors
113
+ * SPDX-License-Identifier: ISC
114
+ */
115
+ // take an un-split argv string and tokenize it.
116
+ function tokenizeArgString(argString) {
117
+ if (Array.isArray(argString)) {
118
+ return argString.map(e => typeof e !== 'string' ? e + '' : e);
119
+ }
120
+ argString = argString.trim();
121
+ let i = 0;
122
+ let prevC = null;
123
+ let c = null;
124
+ let opening = null;
125
+ const args = [];
126
+ for (let ii = 0; ii < argString.length; ii++) {
127
+ prevC = c;
128
+ c = argString.charAt(ii);
129
+ // split on spaces unless we're in quotes.
130
+ if (c === ' ' && !opening) {
131
+ if (!(prevC === ' ')) {
132
+ i++;
133
+ }
134
+ continue;
135
+ }
136
+ // don't split the string if we're in matching
137
+ // opening or closing single and double quotes.
138
+ if (c === opening) {
139
+ opening = null;
140
+ }
141
+ else if ((c === "'" || c === '"') && !opening) {
142
+ opening = c;
143
+ }
144
+ if (!args[i])
145
+ args[i] = '';
146
+ args[i] += c;
147
+ }
148
+ return args;
149
+ }
150
+
151
+ /**
152
+ * @license
153
+ * Copyright (c) 2016, Contributors
154
+ * SPDX-License-Identifier: ISC
155
+ */
156
+ var DefaultValuesForTypeKey;
157
+ (function (DefaultValuesForTypeKey) {
158
+ DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
159
+ DefaultValuesForTypeKey["STRING"] = "string";
160
+ DefaultValuesForTypeKey["NUMBER"] = "number";
161
+ DefaultValuesForTypeKey["ARRAY"] = "array";
162
+ })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
163
+
164
+ /**
165
+ * @license
166
+ * Copyright (c) 2016, Contributors
167
+ * SPDX-License-Identifier: ISC
168
+ */
169
+ let mixin;
170
+ class YargsParser {
171
+ constructor(_mixin) {
172
+ mixin = _mixin;
173
+ }
174
+ parse(argsInput, options) {
175
+ const opts = Object.assign({
176
+ alias: undefined,
177
+ array: undefined,
178
+ boolean: undefined,
179
+ config: undefined,
180
+ configObjects: undefined,
181
+ configuration: undefined,
182
+ coerce: undefined,
183
+ count: undefined,
184
+ default: undefined,
185
+ envPrefix: undefined,
186
+ narg: undefined,
187
+ normalize: undefined,
188
+ string: undefined,
189
+ number: undefined,
190
+ __: undefined,
191
+ key: undefined
192
+ }, options);
193
+ // allow a string argument to be passed in rather
194
+ // than an argv array.
195
+ const args = tokenizeArgString(argsInput);
196
+ // aliases might have transitive relationships, normalize this.
197
+ const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
198
+ const configuration = Object.assign({
199
+ 'boolean-negation': true,
200
+ 'camel-case-expansion': true,
201
+ 'combine-arrays': false,
202
+ 'dot-notation': true,
203
+ 'duplicate-arguments-array': true,
204
+ 'flatten-duplicate-arrays': true,
205
+ 'greedy-arrays': true,
206
+ 'halt-at-non-option': false,
207
+ 'nargs-eats-options': false,
208
+ 'negation-prefix': 'no-',
209
+ 'parse-numbers': true,
210
+ 'parse-positional-numbers': true,
211
+ 'populate--': false,
212
+ 'set-placeholder-key': false,
213
+ 'short-option-groups': true,
214
+ 'strip-aliased': false,
215
+ 'strip-dashed': false,
216
+ 'unknown-options-as-args': false
217
+ }, opts.configuration);
218
+ const defaults = Object.assign(Object.create(null), opts.default);
219
+ const configObjects = opts.configObjects || [];
220
+ const envPrefix = opts.envPrefix;
221
+ const notFlagsOption = configuration['populate--'];
222
+ const notFlagsArgv = notFlagsOption ? '--' : '_';
223
+ const newAliases = Object.create(null);
224
+ const defaulted = Object.create(null);
225
+ // allow a i18n handler to be passed in, default to a fake one (util.format).
226
+ const __ = opts.__ || mixin.format;
227
+ const flags = {
228
+ aliases: Object.create(null),
229
+ arrays: Object.create(null),
230
+ bools: Object.create(null),
231
+ strings: Object.create(null),
232
+ numbers: Object.create(null),
233
+ counts: Object.create(null),
234
+ normalize: Object.create(null),
235
+ configs: Object.create(null),
236
+ nargs: Object.create(null),
237
+ coercions: Object.create(null),
238
+ keys: []
239
+ };
240
+ const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
241
+ const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
242
+ [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
243
+ const key = typeof opt === 'object' ? opt.key : opt;
244
+ // assign to flags[bools|strings|numbers]
245
+ const assignment = Object.keys(opt).map(function (key) {
246
+ const arrayFlagKeys = {
247
+ boolean: 'bools',
248
+ string: 'strings',
249
+ number: 'numbers'
250
+ };
251
+ return arrayFlagKeys[key];
252
+ }).filter(Boolean).pop();
253
+ // assign key to be coerced
254
+ if (assignment) {
255
+ flags[assignment][key] = true;
256
+ }
257
+ flags.arrays[key] = true;
258
+ flags.keys.push(key);
259
+ });
260
+ [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
261
+ flags.bools[key] = true;
262
+ flags.keys.push(key);
263
+ });
264
+ [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
265
+ flags.strings[key] = true;
266
+ flags.keys.push(key);
267
+ });
268
+ [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
269
+ flags.numbers[key] = true;
270
+ flags.keys.push(key);
271
+ });
272
+ [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
273
+ flags.counts[key] = true;
274
+ flags.keys.push(key);
275
+ });
276
+ [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
277
+ flags.normalize[key] = true;
278
+ flags.keys.push(key);
279
+ });
280
+ if (typeof opts.narg === 'object') {
281
+ Object.entries(opts.narg).forEach(([key, value]) => {
282
+ if (typeof value === 'number') {
283
+ flags.nargs[key] = value;
284
+ flags.keys.push(key);
285
+ }
286
+ });
287
+ }
288
+ if (typeof opts.coerce === 'object') {
289
+ Object.entries(opts.coerce).forEach(([key, value]) => {
290
+ if (typeof value === 'function') {
291
+ flags.coercions[key] = value;
292
+ flags.keys.push(key);
293
+ }
294
+ });
295
+ }
296
+ if (typeof opts.config !== 'undefined') {
297
+ if (Array.isArray(opts.config) || typeof opts.config === 'string') {
298
+ [].concat(opts.config).filter(Boolean).forEach(function (key) {
299
+ flags.configs[key] = true;
300
+ });
301
+ }
302
+ else if (typeof opts.config === 'object') {
303
+ Object.entries(opts.config).forEach(([key, value]) => {
304
+ if (typeof value === 'boolean' || typeof value === 'function') {
305
+ flags.configs[key] = value;
306
+ }
307
+ });
308
+ }
309
+ }
310
+ // create a lookup table that takes into account all
311
+ // combinations of aliases: {f: ['foo'], foo: ['f']}
312
+ extendAliases(opts.key, aliases, opts.default, flags.arrays);
313
+ // apply default values to all aliases.
314
+ Object.keys(defaults).forEach(function (key) {
315
+ (flags.aliases[key] || []).forEach(function (alias) {
316
+ defaults[alias] = defaults[key];
317
+ });
318
+ });
319
+ let error = null;
320
+ checkConfiguration();
321
+ let notFlags = [];
322
+ const argv = Object.assign(Object.create(null), { _: [] });
323
+ // TODO(bcoe): for the first pass at removing object prototype we didn't
324
+ // remove all prototypes from objects returned by this API, we might want
325
+ // to gradually move towards doing so.
326
+ const argvReturn = {};
327
+ for (let i = 0; i < args.length; i++) {
328
+ const arg = args[i];
329
+ const truncatedArg = arg.replace(/^-{3,}/, '---');
330
+ let broken;
331
+ let key;
332
+ let letters;
333
+ let m;
334
+ let next;
335
+ let value;
336
+ // any unknown option (except for end-of-options, "--")
337
+ if (arg !== '--' && isUnknownOptionAsArg(arg)) {
338
+ pushPositional(arg);
339
+ // ---, ---=, ----, etc,
340
+ }
341
+ else if (truncatedArg.match(/---+(=|$)/)) {
342
+ // options without key name are invalid.
343
+ pushPositional(arg);
344
+ continue;
345
+ // -- separated by =
346
+ }
347
+ else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
348
+ // Using [\s\S] instead of . because js doesn't support the
349
+ // 'dotall' regex modifier. See:
350
+ // http://stackoverflow.com/a/1068308/13216
351
+ m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
352
+ // arrays format = '--f=a b c'
353
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
354
+ if (checkAllAliases(m[1], flags.arrays)) {
355
+ i = eatArray(i, m[1], args, m[2]);
356
+ }
357
+ else if (checkAllAliases(m[1], flags.nargs) !== false) {
358
+ // nargs format = '--f=monkey washing cat'
359
+ i = eatNargs(i, m[1], args, m[2]);
360
+ }
361
+ else {
362
+ setArg(m[1], m[2]);
363
+ }
364
+ }
365
+ }
366
+ else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
367
+ m = arg.match(negatedBoolean);
368
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
369
+ key = m[1];
370
+ setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
371
+ }
372
+ // -- separated by space.
373
+ }
374
+ else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
375
+ m = arg.match(/^--?(.+)/);
376
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
377
+ key = m[1];
378
+ if (checkAllAliases(key, flags.arrays)) {
379
+ // array format = '--foo a b c'
380
+ i = eatArray(i, key, args);
381
+ }
382
+ else if (checkAllAliases(key, flags.nargs) !== false) {
383
+ // nargs format = '--foo a b c'
384
+ // should be truthy even if: flags.nargs[key] === 0
385
+ i = eatNargs(i, key, args);
386
+ }
387
+ else {
388
+ next = args[i + 1];
389
+ if (next !== undefined && (!next.match(/^-/) ||
390
+ next.match(negative)) &&
391
+ !checkAllAliases(key, flags.bools) &&
392
+ !checkAllAliases(key, flags.counts)) {
393
+ setArg(key, next);
394
+ i++;
395
+ }
396
+ else if (/^(true|false)$/.test(next)) {
397
+ setArg(key, next);
398
+ i++;
399
+ }
400
+ else {
401
+ setArg(key, defaultValue(key));
402
+ }
403
+ }
404
+ }
405
+ // dot-notation flag separated by '='.
406
+ }
407
+ else if (arg.match(/^-.\..+=/)) {
408
+ m = arg.match(/^-([^=]+)=([\s\S]*)$/);
409
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
410
+ setArg(m[1], m[2]);
411
+ }
412
+ // dot-notation flag separated by space.
413
+ }
414
+ else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
415
+ next = args[i + 1];
416
+ m = arg.match(/^-(.\..+)/);
417
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
418
+ key = m[1];
419
+ if (next !== undefined && !next.match(/^-/) &&
420
+ !checkAllAliases(key, flags.bools) &&
421
+ !checkAllAliases(key, flags.counts)) {
422
+ setArg(key, next);
423
+ i++;
424
+ }
425
+ else {
426
+ setArg(key, defaultValue(key));
427
+ }
428
+ }
429
+ }
430
+ else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
431
+ letters = arg.slice(1, -1).split('');
432
+ broken = false;
433
+ for (let j = 0; j < letters.length; j++) {
434
+ next = arg.slice(j + 2);
435
+ if (letters[j + 1] && letters[j + 1] === '=') {
436
+ value = arg.slice(j + 3);
437
+ key = letters[j];
438
+ if (checkAllAliases(key, flags.arrays)) {
439
+ // array format = '-f=a b c'
440
+ i = eatArray(i, key, args, value);
441
+ }
442
+ else if (checkAllAliases(key, flags.nargs) !== false) {
443
+ // nargs format = '-f=monkey washing cat'
444
+ i = eatNargs(i, key, args, value);
445
+ }
446
+ else {
447
+ setArg(key, value);
448
+ }
449
+ broken = true;
450
+ break;
451
+ }
452
+ if (next === '-') {
453
+ setArg(letters[j], next);
454
+ continue;
455
+ }
456
+ // current letter is an alphabetic character and next value is a number
457
+ if (/[A-Za-z]/.test(letters[j]) &&
458
+ /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
459
+ checkAllAliases(next, flags.bools) === false) {
460
+ setArg(letters[j], next);
461
+ broken = true;
462
+ break;
463
+ }
464
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
465
+ setArg(letters[j], next);
466
+ broken = true;
467
+ break;
468
+ }
469
+ else {
470
+ setArg(letters[j], defaultValue(letters[j]));
471
+ }
472
+ }
473
+ key = arg.slice(-1)[0];
474
+ if (!broken && key !== '-') {
475
+ if (checkAllAliases(key, flags.arrays)) {
476
+ // array format = '-f a b c'
477
+ i = eatArray(i, key, args);
478
+ }
479
+ else if (checkAllAliases(key, flags.nargs) !== false) {
480
+ // nargs format = '-f a b c'
481
+ // should be truthy even if: flags.nargs[key] === 0
482
+ i = eatNargs(i, key, args);
483
+ }
484
+ else {
485
+ next = args[i + 1];
486
+ if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
487
+ next.match(negative)) &&
488
+ !checkAllAliases(key, flags.bools) &&
489
+ !checkAllAliases(key, flags.counts)) {
490
+ setArg(key, next);
491
+ i++;
492
+ }
493
+ else if (/^(true|false)$/.test(next)) {
494
+ setArg(key, next);
495
+ i++;
496
+ }
497
+ else {
498
+ setArg(key, defaultValue(key));
499
+ }
500
+ }
501
+ }
502
+ }
503
+ else if (arg.match(/^-[0-9]$/) &&
504
+ arg.match(negative) &&
505
+ checkAllAliases(arg.slice(1), flags.bools)) {
506
+ // single-digit boolean alias, e.g: xargs -0
507
+ key = arg.slice(1);
508
+ setArg(key, defaultValue(key));
509
+ }
510
+ else if (arg === '--') {
511
+ notFlags = args.slice(i + 1);
512
+ break;
513
+ }
514
+ else if (configuration['halt-at-non-option']) {
515
+ notFlags = args.slice(i);
516
+ break;
517
+ }
518
+ else {
519
+ pushPositional(arg);
520
+ }
521
+ }
522
+ // order of precedence:
523
+ // 1. command line arg
524
+ // 2. value from env var
525
+ // 3. value from config file
526
+ // 4. value from config objects
527
+ // 5. configured default value
528
+ applyEnvVars(argv, true); // special case: check env vars that point to config file
529
+ applyEnvVars(argv, false);
530
+ setConfig(argv);
531
+ setConfigObjects();
532
+ applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
533
+ applyCoercions(argv);
534
+ if (configuration['set-placeholder-key'])
535
+ setPlaceholderKeys(argv);
536
+ // for any counts either not in args or without an explicit default, set to 0
537
+ Object.keys(flags.counts).forEach(function (key) {
538
+ if (!hasKey(argv, key.split('.')))
539
+ setArg(key, 0);
540
+ });
541
+ // '--' defaults to undefined.
542
+ if (notFlagsOption && notFlags.length)
543
+ argv[notFlagsArgv] = [];
544
+ notFlags.forEach(function (key) {
545
+ argv[notFlagsArgv].push(key);
546
+ });
547
+ if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
548
+ Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
549
+ delete argv[key];
550
+ });
551
+ }
552
+ if (configuration['strip-aliased']) {
553
+ [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
554
+ if (configuration['camel-case-expansion'] && alias.includes('-')) {
555
+ delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
556
+ }
557
+ delete argv[alias];
558
+ });
559
+ }
560
+ // Push argument into positional array, applying numeric coercion:
561
+ function pushPositional(arg) {
562
+ const maybeCoercedNumber = maybeCoerceNumber('_', arg);
563
+ if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
564
+ argv._.push(maybeCoercedNumber);
565
+ }
566
+ }
567
+ // how many arguments should we consume, based
568
+ // on the nargs option?
569
+ function eatNargs(i, key, args, argAfterEqualSign) {
570
+ let ii;
571
+ let toEat = checkAllAliases(key, flags.nargs);
572
+ // NaN has a special meaning for the array type, indicating that one or
573
+ // more values are expected.
574
+ toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
575
+ if (toEat === 0) {
576
+ if (!isUndefined(argAfterEqualSign)) {
577
+ error = Error(__('Argument unexpected for: %s', key));
578
+ }
579
+ setArg(key, defaultValue(key));
580
+ return i;
581
+ }
582
+ let available = isUndefined(argAfterEqualSign) ? 0 : 1;
583
+ if (configuration['nargs-eats-options']) {
584
+ // classic behavior, yargs eats positional and dash arguments.
585
+ if (args.length - (i + 1) + available < toEat) {
586
+ error = Error(__('Not enough arguments following: %s', key));
587
+ }
588
+ available = toEat;
589
+ }
590
+ else {
591
+ // nargs will not consume flag arguments, e.g., -abc, --foo,
592
+ // and terminates when one is observed.
593
+ for (ii = i + 1; ii < args.length; ii++) {
594
+ if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
595
+ available++;
596
+ else
597
+ break;
598
+ }
599
+ if (available < toEat)
600
+ error = Error(__('Not enough arguments following: %s', key));
601
+ }
602
+ let consumed = Math.min(available, toEat);
603
+ if (!isUndefined(argAfterEqualSign) && consumed > 0) {
604
+ setArg(key, argAfterEqualSign);
605
+ consumed--;
606
+ }
607
+ for (ii = i + 1; ii < (consumed + i + 1); ii++) {
608
+ setArg(key, args[ii]);
609
+ }
610
+ return (i + consumed);
611
+ }
612
+ // if an option is an array, eat all non-hyphenated arguments
613
+ // following it... YUM!
614
+ // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
615
+ function eatArray(i, key, args, argAfterEqualSign) {
616
+ let argsToSet = [];
617
+ let next = argAfterEqualSign || args[i + 1];
618
+ // If both array and nargs are configured, enforce the nargs count:
619
+ const nargsCount = checkAllAliases(key, flags.nargs);
620
+ if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
621
+ argsToSet.push(true);
622
+ }
623
+ else if (isUndefined(next) ||
624
+ (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
625
+ // for keys without value ==> argsToSet remains an empty []
626
+ // set user default value, if available
627
+ if (defaults[key] !== undefined) {
628
+ const defVal = defaults[key];
629
+ argsToSet = Array.isArray(defVal) ? defVal : [defVal];
630
+ }
631
+ }
632
+ else {
633
+ // value in --option=value is eaten as is
634
+ if (!isUndefined(argAfterEqualSign)) {
635
+ argsToSet.push(processValue(key, argAfterEqualSign));
636
+ }
637
+ for (let ii = i + 1; ii < args.length; ii++) {
638
+ if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
639
+ (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
640
+ break;
641
+ next = args[ii];
642
+ if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
643
+ break;
644
+ i = ii;
645
+ argsToSet.push(processValue(key, next));
646
+ }
647
+ }
648
+ // If both array and nargs are configured, create an error if less than
649
+ // nargs positionals were found. NaN has special meaning, indicating
650
+ // that at least one value is required (more are okay).
651
+ if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
652
+ (isNaN(nargsCount) && argsToSet.length === 0))) {
653
+ error = Error(__('Not enough arguments following: %s', key));
654
+ }
655
+ setArg(key, argsToSet);
656
+ return i;
657
+ }
658
+ function setArg(key, val) {
659
+ if (/-/.test(key) && configuration['camel-case-expansion']) {
660
+ const alias = key.split('.').map(function (prop) {
661
+ return camelCase(prop);
662
+ }).join('.');
663
+ addNewAlias(key, alias);
664
+ }
665
+ const value = processValue(key, val);
666
+ const splitKey = key.split('.');
667
+ setKey(argv, splitKey, value);
668
+ // handle populating aliases of the full key
669
+ if (flags.aliases[key]) {
670
+ flags.aliases[key].forEach(function (x) {
671
+ const keyProperties = x.split('.');
672
+ setKey(argv, keyProperties, value);
673
+ });
674
+ }
675
+ // handle populating aliases of the first element of the dot-notation key
676
+ if (splitKey.length > 1 && configuration['dot-notation']) {
677
+ (flags.aliases[splitKey[0]] || []).forEach(function (x) {
678
+ let keyProperties = x.split('.');
679
+ // expand alias with nested objects in key
680
+ const a = [].concat(splitKey);
681
+ a.shift(); // nuke the old key.
682
+ keyProperties = keyProperties.concat(a);
683
+ // populate alias only if is not already an alias of the full key
684
+ // (already populated above)
685
+ if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
686
+ setKey(argv, keyProperties, value);
687
+ }
688
+ });
689
+ }
690
+ // Set normalize getter and setter when key is in 'normalize' but isn't an array
691
+ if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
692
+ const keys = [key].concat(flags.aliases[key] || []);
693
+ keys.forEach(function (key) {
694
+ Object.defineProperty(argvReturn, key, {
695
+ enumerable: true,
696
+ get() {
697
+ return val;
698
+ },
699
+ set(value) {
700
+ val = typeof value === 'string' ? mixin.normalize(value) : value;
701
+ }
702
+ });
703
+ });
704
+ }
705
+ }
706
+ function addNewAlias(key, alias) {
707
+ if (!(flags.aliases[key] && flags.aliases[key].length)) {
708
+ flags.aliases[key] = [alias];
709
+ newAliases[alias] = true;
710
+ }
711
+ if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
712
+ addNewAlias(alias, key);
713
+ }
714
+ }
715
+ function processValue(key, val) {
716
+ // strings may be quoted, clean this up as we assign values.
717
+ if (typeof val === 'string' &&
718
+ (val[0] === "'" || val[0] === '"') &&
719
+ val[val.length - 1] === val[0]) {
720
+ val = val.substring(1, val.length - 1);
721
+ }
722
+ // handle parsing boolean arguments --foo=true --bar false.
723
+ if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
724
+ if (typeof val === 'string')
725
+ val = val === 'true';
726
+ }
727
+ let value = Array.isArray(val)
728
+ ? val.map(function (v) { return maybeCoerceNumber(key, v); })
729
+ : maybeCoerceNumber(key, val);
730
+ // increment a count given as arg (either no value or value parsed as boolean)
731
+ if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
732
+ value = increment();
733
+ }
734
+ // Set normalized value when key is in 'normalize' and in 'arrays'
735
+ if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
736
+ if (Array.isArray(val))
737
+ value = val.map((val) => { return mixin.normalize(val); });
738
+ else
739
+ value = mixin.normalize(val);
740
+ }
741
+ return value;
742
+ }
743
+ function maybeCoerceNumber(key, value) {
744
+ if (!configuration['parse-positional-numbers'] && key === '_')
745
+ return value;
746
+ if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
747
+ const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
748
+ if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
749
+ value = Number(value);
750
+ }
751
+ }
752
+ return value;
753
+ }
754
+ // set args from config.json file, this should be
755
+ // applied last so that defaults can be applied.
756
+ function setConfig(argv) {
757
+ const configLookup = Object.create(null);
758
+ // expand defaults/aliases, in-case any happen to reference
759
+ // the config.json file.
760
+ applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
761
+ Object.keys(flags.configs).forEach(function (configKey) {
762
+ const configPath = argv[configKey] || configLookup[configKey];
763
+ if (configPath) {
764
+ try {
765
+ let config = null;
766
+ const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
767
+ const resolveConfig = flags.configs[configKey];
768
+ if (typeof resolveConfig === 'function') {
769
+ try {
770
+ config = resolveConfig(resolvedConfigPath);
771
+ }
772
+ catch (e) {
773
+ config = e;
774
+ }
775
+ if (config instanceof Error) {
776
+ error = config;
777
+ return;
778
+ }
779
+ }
780
+ else {
781
+ config = mixin.require(resolvedConfigPath);
782
+ }
783
+ setConfigObject(config);
784
+ }
785
+ catch (ex) {
786
+ // Deno will receive a PermissionDenied error if an attempt is
787
+ // made to load config without the --allow-read flag:
788
+ if (ex.name === 'PermissionDenied')
789
+ error = ex;
790
+ else if (argv[configKey])
791
+ error = Error(__('Invalid JSON config file: %s', configPath));
792
+ }
793
+ }
794
+ });
795
+ }
796
+ // set args from config object.
797
+ // it recursively checks nested objects.
798
+ function setConfigObject(config, prev) {
799
+ Object.keys(config).forEach(function (key) {
800
+ const value = config[key];
801
+ const fullKey = prev ? prev + '.' + key : key;
802
+ // if the value is an inner object and we have dot-notation
803
+ // enabled, treat inner objects in config the same as
804
+ // heavily nested dot notations (foo.bar.apple).
805
+ if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
806
+ // if the value is an object but not an array, check nested object
807
+ setConfigObject(value, fullKey);
808
+ }
809
+ else {
810
+ // setting arguments via CLI takes precedence over
811
+ // values within the config file.
812
+ if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
813
+ setArg(fullKey, value);
814
+ }
815
+ }
816
+ });
817
+ }
818
+ // set all config objects passed in opts
819
+ function setConfigObjects() {
820
+ if (typeof configObjects !== 'undefined') {
821
+ configObjects.forEach(function (configObject) {
822
+ setConfigObject(configObject);
823
+ });
824
+ }
825
+ }
826
+ function applyEnvVars(argv, configOnly) {
827
+ if (typeof envPrefix === 'undefined')
828
+ return;
829
+ const prefix = typeof envPrefix === 'string' ? envPrefix : '';
830
+ const env = mixin.env();
831
+ Object.keys(env).forEach(function (envVar) {
832
+ if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
833
+ // get array of nested keys and convert them to camel case
834
+ const keys = envVar.split('__').map(function (key, i) {
835
+ if (i === 0) {
836
+ key = key.substring(prefix.length);
837
+ }
838
+ return camelCase(key);
839
+ });
840
+ if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
841
+ setArg(keys.join('.'), env[envVar]);
842
+ }
843
+ }
844
+ });
845
+ }
846
+ function applyCoercions(argv) {
847
+ let coerce;
848
+ const applied = new Set();
849
+ Object.keys(argv).forEach(function (key) {
850
+ if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
851
+ coerce = checkAllAliases(key, flags.coercions);
852
+ if (typeof coerce === 'function') {
853
+ try {
854
+ const value = maybeCoerceNumber(key, coerce(argv[key]));
855
+ ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
856
+ applied.add(ali);
857
+ argv[ali] = value;
858
+ });
859
+ }
860
+ catch (err) {
861
+ error = err;
862
+ }
863
+ }
864
+ }
865
+ });
866
+ }
867
+ function setPlaceholderKeys(argv) {
868
+ flags.keys.forEach((key) => {
869
+ // don't set placeholder keys for dot notation options 'foo.bar'.
870
+ if (~key.indexOf('.'))
871
+ return;
872
+ if (typeof argv[key] === 'undefined')
873
+ argv[key] = undefined;
874
+ });
875
+ return argv;
876
+ }
877
+ function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
878
+ Object.keys(defaults).forEach(function (key) {
879
+ if (!hasKey(obj, key.split('.'))) {
880
+ setKey(obj, key.split('.'), defaults[key]);
881
+ if (canLog)
882
+ defaulted[key] = true;
883
+ (aliases[key] || []).forEach(function (x) {
884
+ if (hasKey(obj, x.split('.')))
885
+ return;
886
+ setKey(obj, x.split('.'), defaults[key]);
887
+ });
888
+ }
889
+ });
890
+ }
891
+ function hasKey(obj, keys) {
892
+ let o = obj;
893
+ if (!configuration['dot-notation'])
894
+ keys = [keys.join('.')];
895
+ keys.slice(0, -1).forEach(function (key) {
896
+ o = (o[key] || {});
897
+ });
898
+ const key = keys[keys.length - 1];
899
+ if (typeof o !== 'object')
900
+ return false;
901
+ else
902
+ return key in o;
903
+ }
904
+ function setKey(obj, keys, value) {
905
+ let o = obj;
906
+ if (!configuration['dot-notation'])
907
+ keys = [keys.join('.')];
908
+ keys.slice(0, -1).forEach(function (key) {
909
+ // TODO(bcoe): in the next major version of yargs, switch to
910
+ // Object.create(null) for dot notation:
911
+ key = sanitizeKey(key);
912
+ if (typeof o === 'object' && o[key] === undefined) {
913
+ o[key] = {};
914
+ }
915
+ if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
916
+ // ensure that o[key] is an array, and that the last item is an empty object.
917
+ if (Array.isArray(o[key])) {
918
+ o[key].push({});
919
+ }
920
+ else {
921
+ o[key] = [o[key], {}];
922
+ }
923
+ // we want to update the empty object at the end of the o[key] array, so set o to that object
924
+ o = o[key][o[key].length - 1];
925
+ }
926
+ else {
927
+ o = o[key];
928
+ }
929
+ });
930
+ // TODO(bcoe): in the next major version of yargs, switch to
931
+ // Object.create(null) for dot notation:
932
+ const key = sanitizeKey(keys[keys.length - 1]);
933
+ const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
934
+ const isValueArray = Array.isArray(value);
935
+ let duplicate = configuration['duplicate-arguments-array'];
936
+ // nargs has higher priority than duplicate
937
+ if (!duplicate && checkAllAliases(key, flags.nargs)) {
938
+ duplicate = true;
939
+ if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
940
+ o[key] = undefined;
941
+ }
942
+ }
943
+ if (value === increment()) {
944
+ o[key] = increment(o[key]);
945
+ }
946
+ else if (Array.isArray(o[key])) {
947
+ if (duplicate && isTypeArray && isValueArray) {
948
+ o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
949
+ }
950
+ else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
951
+ o[key] = value;
952
+ }
953
+ else {
954
+ o[key] = o[key].concat([value]);
955
+ }
956
+ }
957
+ else if (o[key] === undefined && isTypeArray) {
958
+ o[key] = isValueArray ? value : [value];
959
+ }
960
+ else if (duplicate && !(o[key] === undefined ||
961
+ checkAllAliases(key, flags.counts) ||
962
+ checkAllAliases(key, flags.bools))) {
963
+ o[key] = [o[key], value];
964
+ }
965
+ else {
966
+ o[key] = value;
967
+ }
968
+ }
969
+ // extend the aliases list with inferred aliases.
970
+ function extendAliases(...args) {
971
+ args.forEach(function (obj) {
972
+ Object.keys(obj || {}).forEach(function (key) {
973
+ // short-circuit if we've already added a key
974
+ // to the aliases array, for example it might
975
+ // exist in both 'opts.default' and 'opts.key'.
976
+ if (flags.aliases[key])
977
+ return;
978
+ flags.aliases[key] = [].concat(aliases[key] || []);
979
+ // For "--option-name", also set argv.optionName
980
+ flags.aliases[key].concat(key).forEach(function (x) {
981
+ if (/-/.test(x) && configuration['camel-case-expansion']) {
982
+ const c = camelCase(x);
983
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
984
+ flags.aliases[key].push(c);
985
+ newAliases[c] = true;
986
+ }
987
+ }
988
+ });
989
+ // For "--optionName", also set argv['option-name']
990
+ flags.aliases[key].concat(key).forEach(function (x) {
991
+ if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
992
+ const c = decamelize(x, '-');
993
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
994
+ flags.aliases[key].push(c);
995
+ newAliases[c] = true;
996
+ }
997
+ }
998
+ });
999
+ flags.aliases[key].forEach(function (x) {
1000
+ flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
1001
+ return x !== y;
1002
+ }));
1003
+ });
1004
+ });
1005
+ });
1006
+ }
1007
+ function checkAllAliases(key, flag) {
1008
+ const toCheck = [].concat(flags.aliases[key] || [], key);
1009
+ const keys = Object.keys(flag);
1010
+ const setAlias = toCheck.find(key => keys.includes(key));
1011
+ return setAlias ? flag[setAlias] : false;
1012
+ }
1013
+ function hasAnyFlag(key) {
1014
+ const flagsKeys = Object.keys(flags);
1015
+ const toCheck = [].concat(flagsKeys.map(k => flags[k]));
1016
+ return toCheck.some(function (flag) {
1017
+ return Array.isArray(flag) ? flag.includes(key) : flag[key];
1018
+ });
1019
+ }
1020
+ function hasFlagsMatching(arg, ...patterns) {
1021
+ const toCheck = [].concat(...patterns);
1022
+ return toCheck.some(function (pattern) {
1023
+ const match = arg.match(pattern);
1024
+ return match && hasAnyFlag(match[1]);
1025
+ });
1026
+ }
1027
+ // based on a simplified version of the short flag group parsing logic
1028
+ function hasAllShortFlags(arg) {
1029
+ // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
1030
+ if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
1031
+ return false;
1032
+ }
1033
+ let hasAllFlags = true;
1034
+ let next;
1035
+ const letters = arg.slice(1).split('');
1036
+ for (let j = 0; j < letters.length; j++) {
1037
+ next = arg.slice(j + 2);
1038
+ if (!hasAnyFlag(letters[j])) {
1039
+ hasAllFlags = false;
1040
+ break;
1041
+ }
1042
+ if ((letters[j + 1] && letters[j + 1] === '=') ||
1043
+ next === '-' ||
1044
+ (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
1045
+ (letters[j + 1] && letters[j + 1].match(/\W/))) {
1046
+ break;
1047
+ }
1048
+ }
1049
+ return hasAllFlags;
1050
+ }
1051
+ function isUnknownOptionAsArg(arg) {
1052
+ return configuration['unknown-options-as-args'] && isUnknownOption(arg);
1053
+ }
1054
+ function isUnknownOption(arg) {
1055
+ arg = arg.replace(/^-{3,}/, '--');
1056
+ // ignore negative numbers
1057
+ if (arg.match(negative)) {
1058
+ return false;
1059
+ }
1060
+ // if this is a short option group and all of them are configured, it isn't unknown
1061
+ if (hasAllShortFlags(arg)) {
1062
+ return false;
1063
+ }
1064
+ // e.g. '--count=2'
1065
+ const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
1066
+ // e.g. '-a' or '--arg'
1067
+ const normalFlag = /^-+([^=]+?)$/;
1068
+ // e.g. '-a-'
1069
+ const flagEndingInHyphen = /^-+([^=]+?)-$/;
1070
+ // e.g. '-abc123'
1071
+ const flagEndingInDigits = /^-+([^=]+?\d+)$/;
1072
+ // e.g. '-a/usr/local'
1073
+ const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
1074
+ // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
1075
+ return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
1076
+ }
1077
+ // make a best effort to pick a default value
1078
+ // for an option based on name and type.
1079
+ function defaultValue(key) {
1080
+ if (!checkAllAliases(key, flags.bools) &&
1081
+ !checkAllAliases(key, flags.counts) &&
1082
+ `${key}` in defaults) {
1083
+ return defaults[key];
1084
+ }
1085
+ else {
1086
+ return defaultForType(guessType(key));
1087
+ }
1088
+ }
1089
+ // return a default value, given the type of a flag.,
1090
+ function defaultForType(type) {
1091
+ const def = {
1092
+ [DefaultValuesForTypeKey.BOOLEAN]: true,
1093
+ [DefaultValuesForTypeKey.STRING]: '',
1094
+ [DefaultValuesForTypeKey.NUMBER]: undefined,
1095
+ [DefaultValuesForTypeKey.ARRAY]: []
1096
+ };
1097
+ return def[type];
1098
+ }
1099
+ // given a flag, enforce a default type.
1100
+ function guessType(key) {
1101
+ let type = DefaultValuesForTypeKey.BOOLEAN;
1102
+ if (checkAllAliases(key, flags.strings))
1103
+ type = DefaultValuesForTypeKey.STRING;
1104
+ else if (checkAllAliases(key, flags.numbers))
1105
+ type = DefaultValuesForTypeKey.NUMBER;
1106
+ else if (checkAllAliases(key, flags.bools))
1107
+ type = DefaultValuesForTypeKey.BOOLEAN;
1108
+ else if (checkAllAliases(key, flags.arrays))
1109
+ type = DefaultValuesForTypeKey.ARRAY;
1110
+ return type;
1111
+ }
1112
+ function isUndefined(num) {
1113
+ return num === undefined;
1114
+ }
1115
+ // check user configuration settings for inconsistencies
1116
+ function checkConfiguration() {
1117
+ // count keys should not be set as array/narg
1118
+ Object.keys(flags.counts).find(key => {
1119
+ if (checkAllAliases(key, flags.arrays)) {
1120
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
1121
+ return true;
1122
+ }
1123
+ else if (checkAllAliases(key, flags.nargs)) {
1124
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
1125
+ return true;
1126
+ }
1127
+ return false;
1128
+ });
1129
+ }
1130
+ return {
1131
+ aliases: Object.assign({}, flags.aliases),
1132
+ argv: Object.assign(argvReturn, argv),
1133
+ configuration: configuration,
1134
+ defaulted: Object.assign({}, defaulted),
1135
+ error: error,
1136
+ newAliases: Object.assign({}, newAliases)
1137
+ };
1138
+ }
1139
+ }
1140
+ // if any aliases reference each other, we should
1141
+ // merge them together.
1142
+ function combineAliases(aliases) {
1143
+ const aliasArrays = [];
1144
+ const combined = Object.create(null);
1145
+ let change = true;
1146
+ // turn alias lookup hash {key: ['alias1', 'alias2']} into
1147
+ // a simple array ['key', 'alias1', 'alias2']
1148
+ Object.keys(aliases).forEach(function (key) {
1149
+ aliasArrays.push([].concat(aliases[key], key));
1150
+ });
1151
+ // combine arrays until zero changes are
1152
+ // made in an iteration.
1153
+ while (change) {
1154
+ change = false;
1155
+ for (let i = 0; i < aliasArrays.length; i++) {
1156
+ for (let ii = i + 1; ii < aliasArrays.length; ii++) {
1157
+ const intersect = aliasArrays[i].filter(function (v) {
1158
+ return aliasArrays[ii].indexOf(v) !== -1;
1159
+ });
1160
+ if (intersect.length) {
1161
+ aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
1162
+ aliasArrays.splice(ii, 1);
1163
+ change = true;
1164
+ break;
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ // map arrays back to the hash-lookup (de-dupe while
1170
+ // we're at it).
1171
+ aliasArrays.forEach(function (aliasArray) {
1172
+ aliasArray = aliasArray.filter(function (v, i, self) {
1173
+ return self.indexOf(v) === i;
1174
+ });
1175
+ const lastAlias = aliasArray.pop();
1176
+ if (lastAlias !== undefined && typeof lastAlias === 'string') {
1177
+ combined[lastAlias] = aliasArray;
1178
+ }
1179
+ });
1180
+ return combined;
1181
+ }
1182
+ // this function should only be called when a count is given as an arg
1183
+ // it is NOT called to set a default value
1184
+ // thus we can start the count at 1 instead of 0
1185
+ function increment(orig) {
1186
+ return orig !== undefined ? orig + 1 : 1;
1187
+ }
1188
+ // TODO(bcoe): in the next major version of yargs, switch to
1189
+ // Object.create(null) for dot notation:
1190
+ function sanitizeKey(key) {
1191
+ if (key === '__proto__')
1192
+ return '___proto___';
1193
+ return key;
1194
+ }
1195
+
1196
+ /**
1197
+ * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
1198
+ * CJS and ESM environments.
1199
+ *
1200
+ * @license
1201
+ * Copyright (c) 2016, Contributors
1202
+ * SPDX-License-Identifier: ISC
1203
+ */
1204
+ // See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
1205
+ // version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
1206
+ const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
1207
+ ? Number(process.env.YARGS_MIN_NODE_VERSION)
1208
+ : 10;
1209
+ if (process && process.version) {
1210
+ const major = Number(process.version.match(/v([^.]+)/)[1]);
1211
+ if (major < minNodeVersion) {
1212
+ throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
1213
+ }
1214
+ }
1215
+ // Creates a yargs-parser instance using Node.js standard libraries:
1216
+ const env = process ? process.env : {};
1217
+ const parser = new YargsParser({
1218
+ cwd: process.cwd,
1219
+ env: () => {
1220
+ return env;
1221
+ },
1222
+ format: require$$2.format,
1223
+ normalize: path$1.normalize,
1224
+ resolve: path$1.resolve,
1225
+ // TODO: figure out a way to combine ESM and CJS coverage, such that
1226
+ // we can exercise all the lines below:
1227
+ require: (path) => {
1228
+ if (typeof require !== 'undefined') {
1229
+ return require(path);
1230
+ }
1231
+ else if (path.match(/\.json$/)) {
1232
+ return fs.readFileSync(path, 'utf8');
1233
+ }
1234
+ else {
1235
+ throw Error('only .json config files are supported in ESM');
1236
+ }
1237
+ }
1238
+ });
1239
+ const yargsParser = function Parser(args, opts) {
1240
+ const result = parser.parse(args.slice(), opts);
1241
+ return result.argv;
1242
+ };
1243
+ yargsParser.detailed = function (args, opts) {
1244
+ return parser.parse(args.slice(), opts);
1245
+ };
1246
+ yargsParser.camelCase = camelCase;
1247
+ yargsParser.decamelize = decamelize;
1248
+ yargsParser.looksLikeNumber = looksLikeNumber;
1249
+ var argParser = yargsParser;
1250
+
1251
+ var parseMs = milliseconds => {
1252
+ if (typeof milliseconds !== 'number') {
1253
+ throw new TypeError('Expected a number');
1254
+ }
1255
+
1256
+ const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil;
1257
+
1258
+ return {
1259
+ days: roundTowardsZero(milliseconds / 86400000),
1260
+ hours: roundTowardsZero(milliseconds / 3600000) % 24,
1261
+ minutes: roundTowardsZero(milliseconds / 60000) % 60,
1262
+ seconds: roundTowardsZero(milliseconds / 1000) % 60,
1263
+ milliseconds: roundTowardsZero(milliseconds) % 1000,
1264
+ microseconds: roundTowardsZero(milliseconds * 1000) % 1000,
1265
+ nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000
1266
+ };
1267
+ };
1268
+
1269
+ const parseMilliseconds = parseMs;
1270
+
1271
+ const pluralize = (word, count) => count === 1 ? word : `${word}s`;
1272
+
1273
+ const SECOND_ROUNDING_EPSILON = 0.0000001;
1274
+
1275
+ var prettyMs = (milliseconds, options = {}) => {
1276
+ if (!Number.isFinite(milliseconds)) {
1277
+ throw new TypeError('Expected a finite number');
1278
+ }
1279
+
1280
+ if (options.colonNotation) {
1281
+ options.compact = false;
1282
+ options.formatSubMilliseconds = false;
1283
+ options.separateMilliseconds = false;
1284
+ options.verbose = false;
1285
+ }
1286
+
1287
+ if (options.compact) {
1288
+ options.secondsDecimalDigits = 0;
1289
+ options.millisecondsDecimalDigits = 0;
1290
+ }
1291
+
1292
+ const result = [];
1293
+
1294
+ const floorDecimals = (value, decimalDigits) => {
1295
+ const flooredInterimValue = Math.floor((value * (10 ** decimalDigits)) + SECOND_ROUNDING_EPSILON);
1296
+ const flooredValue = Math.round(flooredInterimValue) / (10 ** decimalDigits);
1297
+ return flooredValue.toFixed(decimalDigits);
1298
+ };
1299
+
1300
+ const add = (value, long, short, valueString) => {
1301
+ if ((result.length === 0 || !options.colonNotation) && value === 0 && !(options.colonNotation && short === 'm')) {
1302
+ return;
1303
+ }
1304
+
1305
+ valueString = (valueString || value || '0').toString();
1306
+ let prefix;
1307
+ let suffix;
1308
+ if (options.colonNotation) {
1309
+ prefix = result.length > 0 ? ':' : '';
1310
+ suffix = '';
1311
+ const wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length;
1312
+ const minLength = result.length > 0 ? 2 : 1;
1313
+ valueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString;
1314
+ } else {
1315
+ prefix = '';
1316
+ suffix = options.verbose ? ' ' + pluralize(long, value) : short;
1317
+ }
1318
+
1319
+ result.push(prefix + valueString + suffix);
1320
+ };
1321
+
1322
+ const parsed = parseMilliseconds(milliseconds);
1323
+
1324
+ add(Math.trunc(parsed.days / 365), 'year', 'y');
1325
+ add(parsed.days % 365, 'day', 'd');
1326
+ add(parsed.hours, 'hour', 'h');
1327
+ add(parsed.minutes, 'minute', 'm');
1328
+
1329
+ if (
1330
+ options.separateMilliseconds ||
1331
+ options.formatSubMilliseconds ||
1332
+ (!options.colonNotation && milliseconds < 1000)
1333
+ ) {
1334
+ add(parsed.seconds, 'second', 's');
1335
+ if (options.formatSubMilliseconds) {
1336
+ add(parsed.milliseconds, 'millisecond', 'ms');
1337
+ add(parsed.microseconds, 'microsecond', 'µs');
1338
+ add(parsed.nanoseconds, 'nanosecond', 'ns');
1339
+ } else {
1340
+ const millisecondsAndBelow =
1341
+ parsed.milliseconds +
1342
+ (parsed.microseconds / 1000) +
1343
+ (parsed.nanoseconds / 1e6);
1344
+
1345
+ const millisecondsDecimalDigits =
1346
+ typeof options.millisecondsDecimalDigits === 'number' ?
1347
+ options.millisecondsDecimalDigits :
1348
+ 0;
1349
+
1350
+ const roundedMiliseconds = millisecondsAndBelow >= 1 ?
1351
+ Math.round(millisecondsAndBelow) :
1352
+ Math.ceil(millisecondsAndBelow);
1353
+
1354
+ const millisecondsString = millisecondsDecimalDigits ?
1355
+ millisecondsAndBelow.toFixed(millisecondsDecimalDigits) :
1356
+ roundedMiliseconds;
1357
+
1358
+ add(
1359
+ Number.parseFloat(millisecondsString, 10),
1360
+ 'millisecond',
1361
+ 'ms',
1362
+ millisecondsString
1363
+ );
1364
+ }
1365
+ } else {
1366
+ const seconds = (milliseconds / 1000) % 60;
1367
+ const secondsDecimalDigits =
1368
+ typeof options.secondsDecimalDigits === 'number' ?
1369
+ options.secondsDecimalDigits :
1370
+ 1;
1371
+ const secondsFixed = floorDecimals(seconds, secondsDecimalDigits);
1372
+ const secondsString = options.keepDecimalsOnWholeSeconds ?
1373
+ secondsFixed :
1374
+ secondsFixed.replace(/\.0+$/, '');
1375
+ add(Number.parseFloat(secondsString, 10), 'second', 's', secondsString);
1376
+ }
1377
+
1378
+ if (result.length === 0) {
1379
+ return '0' + (options.verbose ? ' milliseconds' : 'ms');
1380
+ }
1381
+
1382
+ if (options.compact) {
1383
+ return result[0];
1384
+ }
1385
+
1386
+ if (typeof options.unitCount === 'number') {
1387
+ const separator = options.colonNotation ? '' : ' ';
1388
+ return result.slice(0, Math.max(options.unitCount, 1)).join(separator);
1389
+ }
1390
+
1391
+ return options.colonNotation ? result.join('') : result.join(' ');
1392
+ };
1393
+
1394
+ var ms = prettyMs;
1395
+
1396
+ let SOURCEMAPPING_URL = 'sourceMa';
1397
+ SOURCEMAPPING_URL += 'ppingURL';
1398
+ var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
1399
+
1400
+ const BYTE_UNITS = [
1401
+ 'B',
1402
+ 'kB',
1403
+ 'MB',
1404
+ 'GB',
1405
+ 'TB',
1406
+ 'PB',
1407
+ 'EB',
1408
+ 'ZB',
1409
+ 'YB'
1410
+ ];
1411
+
1412
+ const BIBYTE_UNITS = [
1413
+ 'B',
1414
+ 'kiB',
1415
+ 'MiB',
1416
+ 'GiB',
1417
+ 'TiB',
1418
+ 'PiB',
1419
+ 'EiB',
1420
+ 'ZiB',
1421
+ 'YiB'
1422
+ ];
1423
+
1424
+ const BIT_UNITS = [
1425
+ 'b',
1426
+ 'kbit',
1427
+ 'Mbit',
1428
+ 'Gbit',
1429
+ 'Tbit',
1430
+ 'Pbit',
1431
+ 'Ebit',
1432
+ 'Zbit',
1433
+ 'Ybit'
1434
+ ];
1435
+
1436
+ const BIBIT_UNITS = [
1437
+ 'b',
1438
+ 'kibit',
1439
+ 'Mibit',
1440
+ 'Gibit',
1441
+ 'Tibit',
1442
+ 'Pibit',
1443
+ 'Eibit',
1444
+ 'Zibit',
1445
+ 'Yibit'
1446
+ ];
1447
+
1448
+ /*
1449
+ Formats the given number using `Number#toLocaleString`.
1450
+ - If locale is a string, the value is expected to be a locale-key (for example: `de`).
1451
+ - If locale is true, the system default locale is used for translation.
1452
+ - If no value for locale is specified, the number is returned unmodified.
1453
+ */
1454
+ const toLocaleString = (number, locale, options) => {
1455
+ let result = number;
1456
+ if (typeof locale === 'string' || Array.isArray(locale)) {
1457
+ result = number.toLocaleString(locale, options);
1458
+ } else if (locale === true || options !== undefined) {
1459
+ result = number.toLocaleString(undefined, options);
1460
+ }
1461
+
1462
+ return result;
1463
+ };
1464
+
1465
+ var prettyBytes = (number, options) => {
1466
+ if (!Number.isFinite(number)) {
1467
+ throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
1468
+ }
1469
+
1470
+ options = Object.assign({bits: false, binary: false}, options);
1471
+
1472
+ const UNITS = options.bits ?
1473
+ (options.binary ? BIBIT_UNITS : BIT_UNITS) :
1474
+ (options.binary ? BIBYTE_UNITS : BYTE_UNITS);
1475
+
1476
+ if (options.signed && number === 0) {
1477
+ return ` 0 ${UNITS[0]}`;
1478
+ }
1479
+
1480
+ const isNegative = number < 0;
1481
+ const prefix = isNegative ? '-' : (options.signed ? '+' : '');
1482
+
1483
+ if (isNegative) {
1484
+ number = -number;
1485
+ }
1486
+
1487
+ let localeOptions;
1488
+
1489
+ if (options.minimumFractionDigits !== undefined) {
1490
+ localeOptions = {minimumFractionDigits: options.minimumFractionDigits};
1491
+ }
1492
+
1493
+ if (options.maximumFractionDigits !== undefined) {
1494
+ localeOptions = Object.assign({maximumFractionDigits: options.maximumFractionDigits}, localeOptions);
1495
+ }
1496
+
1497
+ if (number < 1) {
1498
+ const numberString = toLocaleString(number, options.locale, localeOptions);
1499
+ return prefix + numberString + ' ' + UNITS[0];
1500
+ }
1501
+
1502
+ const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
1503
+ // eslint-disable-next-line unicorn/prefer-exponentiation-operator
1504
+ number /= Math.pow(options.binary ? 1024 : 1000, exponent);
1505
+
1506
+ if (!localeOptions) {
1507
+ number = number.toPrecision(3);
1508
+ }
1509
+
1510
+ const numberString = toLocaleString(Number(number), options.locale, localeOptions);
1511
+
1512
+ const unit = UNITS[exponent];
1513
+
1514
+ return prefix + numberString + ' ' + unit;
1515
+ };
1516
+
1517
+ var prettyBytes$1 = prettyBytes;
1518
+
1519
+ function printTimings(timings) {
1520
+ Object.keys(timings).forEach(label => {
1521
+ const appliedColor = label[0] === '#' ? (label[1] !== '#' ? loadConfigFile_js.underline : loadConfigFile_js.bold) : (text) => text;
1522
+ const [time, memory, total] = timings[label];
1523
+ const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes$1(memory)} / ${prettyBytes$1(total)}`;
1524
+ console.info(appliedColor(row));
1525
+ });
1526
+ }
1527
+
1528
+ async function build(inputOptions, warnings, silent = false) {
1529
+ const outputOptions = inputOptions.output;
1530
+ const useStdout = !outputOptions[0].file && !outputOptions[0].dir;
1531
+ const start = Date.now();
1532
+ const files = useStdout ? ['stdout'] : outputOptions.map(t => rollup.relativeId(t.file || t.dir));
1533
+ if (!silent) {
1534
+ let inputFiles;
1535
+ if (typeof inputOptions.input === 'string') {
1536
+ inputFiles = inputOptions.input;
1537
+ }
1538
+ else if (inputOptions.input instanceof Array) {
1539
+ inputFiles = inputOptions.input.join(', ');
1540
+ }
1541
+ else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
1542
+ inputFiles = Object.values(inputOptions.input).join(', ');
1543
+ }
1544
+ loadConfigFile_js.stderr(loadConfigFile_js.cyan(`\n${loadConfigFile_js.bold(inputFiles)} → ${loadConfigFile_js.bold(files.join(', '))}...`));
1545
+ }
1546
+ const bundle = await rollup.rollup(inputOptions);
1547
+ if (useStdout) {
1548
+ const output = outputOptions[0];
1549
+ if (output.sourcemap && output.sourcemap !== 'inline') {
1550
+ loadConfigFile_js.handleError({
1551
+ code: 'ONLY_INLINE_SOURCEMAPS',
1552
+ message: 'Only inline sourcemaps are supported when bundling to stdout.'
1553
+ });
1554
+ }
1555
+ const { output: outputs } = await bundle.generate(output);
1556
+ for (const file of outputs) {
1557
+ let source;
1558
+ if (file.type === 'asset') {
1559
+ source = file.source;
1560
+ }
1561
+ else {
1562
+ source = file.code;
1563
+ if (output.sourcemap === 'inline') {
1564
+ source += `\n//# ${SOURCEMAPPING_URL$1}=${file.map.toUrl()}\n`;
1565
+ }
1566
+ }
1567
+ if (outputs.length > 1)
1568
+ process.stdout.write(`\n${loadConfigFile_js.cyan(loadConfigFile_js.bold(`//→ ${file.fileName}:`))}\n`);
1569
+ process.stdout.write(source);
1570
+ }
1571
+ if (!silent) {
1572
+ warnings.flush();
1573
+ }
1574
+ return;
1575
+ }
1576
+ await Promise.all(outputOptions.map(bundle.write));
1577
+ await bundle.close();
1578
+ if (!silent) {
1579
+ warnings.flush();
1580
+ loadConfigFile_js.stderr(loadConfigFile_js.green(`created ${loadConfigFile_js.bold(files.join(', '))} in ${loadConfigFile_js.bold(ms(Date.now() - start))}`));
1581
+ if (bundle && bundle.getTimings) {
1582
+ printTimings(bundle.getTimings());
1583
+ }
1584
+ }
1585
+ }
1586
+
1587
+ /*
1588
+ relative require
1589
+ */
1590
+
1591
+ var path = path$1;
1592
+ var Module = require$$1;
1593
+
1594
+ var modules = {};
1595
+
1596
+ var getModule = function(dir) {
1597
+ var rootPath = dir ? path.resolve(dir) : process.cwd();
1598
+ var rootName = path.join(rootPath, '@root');
1599
+ var root = modules[rootName];
1600
+ if (!root) {
1601
+ root = new Module(rootName);
1602
+ root.filename = rootName;
1603
+ root.paths = Module._nodeModulePaths(rootPath);
1604
+ modules[rootName] = root;
1605
+ }
1606
+ return root;
1607
+ };
1608
+
1609
+ var requireRelative = function(requested, relativeTo) {
1610
+ var root = getModule(relativeTo);
1611
+ return root.require(requested);
1612
+ };
1613
+
1614
+ requireRelative.resolve = function(requested, relativeTo) {
1615
+ var root = getModule(relativeTo);
1616
+ return Module._resolveFilename(requested, root);
1617
+ };
1618
+
1619
+ var requireRelative_1 = requireRelative;
1620
+
1621
+ var relative = requireRelative_1;
1622
+
1623
+ const DEFAULT_CONFIG_BASE = 'rollup.config';
1624
+ function getConfigPath(commandConfig) {
1625
+ const cwd = process.cwd();
1626
+ if (commandConfig === true) {
1627
+ return path__namespace.resolve(findConfigFileNameInCwd());
1628
+ }
1629
+ if (commandConfig.slice(0, 5) === 'node:') {
1630
+ const pkgName = commandConfig.slice(5);
1631
+ try {
1632
+ return relative.resolve(`rollup-config-${pkgName}`, cwd);
1633
+ }
1634
+ catch (_a) {
1635
+ try {
1636
+ return relative.resolve(pkgName, cwd);
1637
+ }
1638
+ catch (err) {
1639
+ if (err.code === 'MODULE_NOT_FOUND') {
1640
+ loadConfigFile_js.handleError({
1641
+ code: 'MISSING_EXTERNAL_CONFIG',
1642
+ message: `Could not resolve config file "${commandConfig}"`
1643
+ });
1644
+ }
1645
+ throw err;
1646
+ }
1647
+ }
1648
+ }
1649
+ return path__namespace.resolve(commandConfig);
1650
+ }
1651
+ function findConfigFileNameInCwd() {
1652
+ const filesInWorkingDir = new Set(fs.readdirSync(process.cwd()));
1653
+ for (const extension of ['mjs', 'cjs', 'ts']) {
1654
+ const fileName = `${DEFAULT_CONFIG_BASE}.${extension}`;
1655
+ if (filesInWorkingDir.has(fileName))
1656
+ return fileName;
1657
+ }
1658
+ return `${DEFAULT_CONFIG_BASE}.js`;
1659
+ }
1660
+
1661
+ function loadConfigFromCommand(command) {
1662
+ const warnings = loadConfigFile_js.batchWarnings();
1663
+ if (!command.input && (command.stdin || !process.stdin.isTTY)) {
1664
+ command.input = loadConfigFile_js.stdinName;
1665
+ }
1666
+ const options = mergeOptions.mergeOptions({ input: [] }, command, warnings.add);
1667
+ loadConfigFile_js.addCommandPluginsToInputOptions(options, command);
1668
+ return { options: [options], warnings };
1669
+ }
1670
+
1671
+ async function runRollup(command) {
1672
+ let inputSource;
1673
+ if (command._.length > 0) {
1674
+ if (command.input) {
1675
+ loadConfigFile_js.handleError({
1676
+ code: 'DUPLICATE_IMPORT_OPTIONS',
1677
+ message: 'Either use --input, or pass input path as argument'
1678
+ });
1679
+ }
1680
+ inputSource = command._;
1681
+ }
1682
+ else if (typeof command.input === 'string') {
1683
+ inputSource = [command.input];
1684
+ }
1685
+ else {
1686
+ inputSource = command.input;
1687
+ }
1688
+ if (inputSource && inputSource.length > 0) {
1689
+ if (inputSource.some((input) => input.indexOf('=') !== -1)) {
1690
+ command.input = {};
1691
+ inputSource.forEach((input) => {
1692
+ const equalsIndex = input.indexOf('=');
1693
+ const value = input.substr(equalsIndex + 1);
1694
+ let key = input.substr(0, equalsIndex);
1695
+ if (!key)
1696
+ key = rollup.getAliasName(input);
1697
+ command.input[key] = value;
1698
+ });
1699
+ }
1700
+ else {
1701
+ command.input = inputSource;
1702
+ }
1703
+ }
1704
+ if (command.environment) {
1705
+ const environment = Array.isArray(command.environment)
1706
+ ? command.environment
1707
+ : [command.environment];
1708
+ environment.forEach((arg) => {
1709
+ arg.split(',').forEach((pair) => {
1710
+ const [key, ...value] = pair.split(':');
1711
+ if (value.length) {
1712
+ process.env[key] = value.join(':');
1713
+ }
1714
+ else {
1715
+ process.env[key] = String(true);
1716
+ }
1717
+ });
1718
+ });
1719
+ }
1720
+ if (command.watch) {
1721
+ await rollup.loadFsEvents();
1722
+ const { watch } = await Promise.resolve().then(function () { return require('../shared/watch-cli.js'); });
1723
+ watch(command);
1724
+ }
1725
+ else {
1726
+ try {
1727
+ const { options, warnings } = await getConfigs(command);
1728
+ try {
1729
+ for (const inputOptions of options) {
1730
+ await build(inputOptions, warnings, command.silent);
1731
+ }
1732
+ if (command.failAfterWarnings && warnings.warningOccurred) {
1733
+ warnings.flush();
1734
+ loadConfigFile_js.handleError({
1735
+ code: 'FAIL_AFTER_WARNINGS',
1736
+ message: 'Warnings occurred and --failAfterWarnings flag present'
1737
+ });
1738
+ }
1739
+ }
1740
+ catch (err) {
1741
+ warnings.flush();
1742
+ loadConfigFile_js.handleError(err);
1743
+ }
1744
+ }
1745
+ catch (err) {
1746
+ loadConfigFile_js.handleError(err);
1747
+ }
1748
+ }
1749
+ }
1750
+ async function getConfigs(command) {
1751
+ if (command.config) {
1752
+ const configFile = getConfigPath(command.config);
1753
+ const { options, warnings } = await loadConfigFile_js.loadAndParseConfigFile(configFile, command);
1754
+ return { options, warnings };
1755
+ }
1756
+ return loadConfigFromCommand(command);
1757
+ }
1758
+
1759
+ const command = argParser(process.argv.slice(2), {
1760
+ alias: mergeOptions.commandAliases,
1761
+ configuration: { 'camel-case-expansion': false }
1762
+ });
1763
+ if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {
1764
+ console.log(`\n${help.replace('__VERSION__', rollup.version)}\n`);
1765
+ }
1766
+ else if (command.version) {
1767
+ console.log(`rollup v${rollup.version}`);
1768
+ }
1769
+ else {
1770
+ try {
1771
+ require('source-map-support').install();
1772
+ }
1773
+ catch (_a) {
1774
+ // do nothing
1775
+ }
1776
+ runRollup(command);
1777
+ }
1778
+
1779
+ exports.getConfigPath = getConfigPath;
1780
+ exports.loadConfigFromCommand = loadConfigFromCommand;
1781
+ exports.ms = ms;
1782
+ exports.printTimings = printTimings;
1783
+ //# sourceMappingURL=rollup.map