rollup 75 KB

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