UNPKG

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