rollup 73 KB

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