9946eb78730209d8de7b592f8e789faa065908e0ee3f8ec8876b0c2867d00655f36ea59d4abfa42f07f5a7cff29896edc2fd1df2beffedbf961a28a0886206-exec 73 KB

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