cli.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const tty = require("tty");
  8. const webpackSchema =
  9. /** @type {EXPECTED_ANY} */
  10. (require("../schemas/WebpackOptions.json"));
  11. /** @import { JSONSchema4, JSONSchema6, JSONSchema7 } from "json-schema" */
  12. /** @typedef {JSONSchema4 | JSONSchema6 | JSONSchema7} JSONSchema */
  13. /** @typedef {JSONSchema & { absolutePath: boolean, instanceof: string, cli: { helper?: boolean, exclude?: boolean, description?: string, negatedDescription?: string, resetDescription?: string } }} Schema */
  14. /**
  15. * Defines the path item type used by this module.
  16. * @typedef {object} PathItem
  17. * @property {Schema} schema the part of the schema
  18. * @property {string} path the path in the config
  19. * @property {string} segment the JSON pointer segment of this schema part (absolute when starting with "#")
  20. */
  21. /** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "prototype-pollution-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */
  22. /** @typedef {string | number | boolean | RegExp} Value */
  23. /**
  24. * Defines the problem type used by this module.
  25. * @typedef {object} Problem
  26. * @property {ProblemType} type
  27. * @property {string} path
  28. * @property {string} argument
  29. * @property {Value=} value
  30. * @property {number=} index
  31. * @property {string=} expected
  32. */
  33. /**
  34. * Defines the local problem type used by this module.
  35. * @typedef {object} LocalProblem
  36. * @property {ProblemType} type
  37. * @property {string} path
  38. * @property {string=} expected
  39. */
  40. /** @typedef {{ [key: string]: EnumValue }} EnumValueObject */
  41. /** @typedef {EnumValue[]} EnumValueArray */
  42. /** @typedef {string | number | boolean | EnumValueObject | EnumValueArray | null} EnumValue */
  43. /**
  44. * Defines the argument config type used by this module.
  45. * @typedef {object} ArgumentConfig
  46. * @property {string=} description
  47. * @property {string=} negatedDescription
  48. * @property {string} path
  49. * @property {boolean} multiple
  50. * @property {"enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset"} type
  51. * @property {EnumValue[]=} values
  52. */
  53. /** @typedef {"string" | "number" | "boolean"} SimpleType */
  54. /**
  55. * Defines the argument type used by this module.
  56. * @typedef {object} Argument
  57. * @property {string | undefined} description
  58. * @property {SimpleType} simpleType
  59. * @property {boolean} multiple
  60. * @property {ArgumentConfig[]} configs
  61. */
  62. /** @typedef {Record<string, Argument>} Flags */
  63. /** @typedef {Record<string, EXPECTED_ANY>} ObjectConfiguration */
  64. /**
  65. * Returns object of arguments.
  66. * @param {Schema=} schema a json schema to create arguments for (by default webpack schema is used)
  67. * @returns {Flags} object of arguments
  68. */
  69. const getArguments = (schema = webpackSchema) => {
  70. /** @type {Flags} */
  71. const flags = {};
  72. /**
  73. * Path to argument name.
  74. * @param {string} input input
  75. * @returns {string} result
  76. */
  77. const pathToArgumentName = (input) =>
  78. input
  79. .replace(/\./g, "-")
  80. .replace(/\[\]/g, "")
  81. .replace(
  82. /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu,
  83. "$1-$2"
  84. )
  85. .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-")
  86. .toLowerCase();
  87. /**
  88. * Returns schema part.
  89. * @param {string} path path
  90. * @returns {Schema} schema part
  91. */
  92. const getSchemaPart = (path) => {
  93. const newPath = path.split("/");
  94. let schemaPart = schema;
  95. for (let i = 1; i < newPath.length; i++) {
  96. const inner = schemaPart[/** @type {keyof Schema} */ (newPath[i])];
  97. if (!inner) {
  98. break;
  99. }
  100. schemaPart = inner;
  101. }
  102. return schemaPart;
  103. };
  104. /**
  105. * Returns description.
  106. * @param {PathItem[]} path path in the schema
  107. * @returns {string | undefined} description
  108. */
  109. const getDescription = (path) => {
  110. for (const { schema } of path) {
  111. if (schema.cli) {
  112. if (schema.cli.helper) continue;
  113. if (schema.cli.description) return schema.cli.description;
  114. }
  115. if (schema.description) return schema.description;
  116. }
  117. };
  118. /**
  119. * Gets negated description.
  120. * @param {PathItem[]} path path in the schema
  121. * @returns {string | undefined} negative description
  122. */
  123. const getNegatedDescription = (path) => {
  124. for (const { schema } of path) {
  125. if (schema.cli) {
  126. if (schema.cli.helper) continue;
  127. if (schema.cli.negatedDescription) return schema.cli.negatedDescription;
  128. }
  129. }
  130. };
  131. /**
  132. * Gets reset description.
  133. * @param {PathItem[]} path path in the schema
  134. * @returns {string | undefined} reset description
  135. */
  136. const getResetDescription = (path) => {
  137. for (const { schema } of path) {
  138. if (schema.cli) {
  139. if (schema.cli.helper) continue;
  140. if (schema.cli.resetDescription) return schema.cli.resetDescription;
  141. }
  142. }
  143. };
  144. /**
  145. * Schema to argument config.
  146. * @param {Schema} schemaPart schema
  147. * @returns {Pick<ArgumentConfig, "type" | "values"> | undefined} partial argument config
  148. */
  149. const schemaToArgumentConfig = (schemaPart) => {
  150. if (schemaPart.enum) {
  151. return {
  152. type: "enum",
  153. values: schemaPart.enum
  154. };
  155. }
  156. if (schemaPart.const !== undefined) {
  157. return {
  158. type: "enum",
  159. values: [schemaPart.const]
  160. };
  161. }
  162. switch (schemaPart.type) {
  163. case "number":
  164. return {
  165. type: "number"
  166. };
  167. case "string":
  168. return {
  169. type: schemaPart.absolutePath ? "path" : "string"
  170. };
  171. case "boolean":
  172. return {
  173. type: "boolean"
  174. };
  175. }
  176. if (schemaPart.instanceof === "RegExp") {
  177. return {
  178. type: "RegExp"
  179. };
  180. }
  181. return undefined;
  182. };
  183. /**
  184. * Adds the provided path to this object.
  185. * @param {PathItem[]} path path in the schema
  186. * @returns {void}
  187. */
  188. const addResetFlag = (path) => {
  189. const schemaPath = path[0].path;
  190. const name = pathToArgumentName(`${schemaPath}.reset`);
  191. const description =
  192. getResetDescription(path) ||
  193. `Clear all items provided in '${schemaPath}' configuration. ${getDescription(
  194. path
  195. )}`;
  196. flags[name] = {
  197. configs: [
  198. {
  199. type: "reset",
  200. multiple: false,
  201. description,
  202. path: schemaPath
  203. }
  204. ],
  205. description: undefined,
  206. simpleType:
  207. /** @type {SimpleType} */
  208. (/** @type {unknown} */ (undefined)),
  209. multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
  210. };
  211. };
  212. /**
  213. * Joins the per-item segments into a JSON pointer (built only when needed).
  214. * @param {PathItem[]} path full path in schema (deepest item first)
  215. * @returns {string} JSON pointer to the deepest schema part
  216. */
  217. const getOriginPath = (path) => {
  218. let origin = "";
  219. for (let i = path.length - 1; i >= 0; i--) {
  220. const { segment } = path[i];
  221. origin = segment[0] === "#" ? segment : origin + segment;
  222. }
  223. return origin;
  224. };
  225. /**
  226. * Adds the provided path to this object.
  227. * @param {PathItem[]} path full path in schema
  228. * @param {boolean} multiple inside of an array
  229. * @returns {number} number of arguments added
  230. */
  231. const addFlag = (path, multiple) => {
  232. const argConfigBase = schemaToArgumentConfig(path[0].schema);
  233. if (!argConfigBase) return 0;
  234. const negatedDescription = getNegatedDescription(path);
  235. const name = pathToArgumentName(path[0].path);
  236. /** @type {ArgumentConfig} */
  237. const argConfig = {
  238. ...argConfigBase,
  239. multiple,
  240. description: getDescription(path),
  241. path: path[0].path
  242. };
  243. if (negatedDescription) {
  244. argConfig.negatedDescription = negatedDescription;
  245. }
  246. if (!flags[name]) {
  247. flags[name] = {
  248. configs: [],
  249. description: undefined,
  250. simpleType:
  251. /** @type {SimpleType} */
  252. (/** @type {unknown} */ (undefined)),
  253. multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
  254. };
  255. }
  256. if (
  257. flags[name].configs.some(
  258. (item) => JSON.stringify(item) === JSON.stringify(argConfig)
  259. )
  260. ) {
  261. return 0;
  262. }
  263. if (
  264. flags[name].configs.some(
  265. (item) => item.type === argConfig.type && item.multiple !== multiple
  266. )
  267. ) {
  268. if (multiple) {
  269. throw new Error(
  270. `Conflicting schema for ${path[0].path} (${getOriginPath(
  271. path
  272. )}) with ${
  273. argConfig.type
  274. } type (array type must be before single item type)`
  275. );
  276. }
  277. return 0;
  278. }
  279. flags[name].configs.push(argConfig);
  280. return 1;
  281. };
  282. // TODO support `not`
  283. /**
  284. * Returns added arguments.
  285. * @param {Schema} schemaPart the current schema
  286. * @param {string} schemaPath the current path in the config
  287. * @param {PathItem[]} path all previous visited schemaParts
  288. * @param {string | null} inArray if inside of an array, the path to the array
  289. * @param {string} segment the JSON pointer segment of the current schema
  290. * @returns {number} added arguments
  291. */
  292. const traverse = (
  293. schemaPart,
  294. schemaPath = "",
  295. path = [],
  296. inArray = null,
  297. segment = "#"
  298. ) => {
  299. while (schemaPart.$ref) {
  300. segment = schemaPart.$ref;
  301. schemaPart = getSchemaPart(schemaPart.$ref);
  302. }
  303. const repetitions = path.filter(({ schema }) => schema === schemaPart);
  304. if (
  305. repetitions.length >= 2 ||
  306. repetitions.some(({ path }) => path === schemaPath)
  307. ) {
  308. return 0;
  309. }
  310. if (schemaPart.cli && schemaPart.cli.exclude) return 0;
  311. /** @type {PathItem[]} */
  312. const fullPath = [
  313. { schema: schemaPart, path: schemaPath, segment },
  314. ...path
  315. ];
  316. let addedArguments = 0;
  317. addedArguments += addFlag(fullPath, Boolean(inArray));
  318. // Collect flags from both branches of a conditional schema.
  319. const conditional = /** @type {JSONSchema7} */ (schemaPart);
  320. if (conditional.if) {
  321. for (const key of /** @type {const} */ (["if", "then", "else"])) {
  322. const subSchema = conditional[key];
  323. if (subSchema && typeof subSchema === "object") {
  324. addedArguments += traverse(
  325. /** @type {Schema} */
  326. (subSchema),
  327. schemaPath,
  328. fullPath,
  329. inArray,
  330. `/${key}`
  331. );
  332. }
  333. }
  334. }
  335. if (schemaPart.type === "object") {
  336. if (schemaPart.properties) {
  337. for (const property of Object.keys(schemaPart.properties)) {
  338. addedArguments += traverse(
  339. /** @type {Schema} */
  340. (schemaPart.properties[property]),
  341. schemaPath ? `${schemaPath}.${property}` : property,
  342. fullPath,
  343. inArray,
  344. `/properties/${property}`
  345. );
  346. }
  347. }
  348. return addedArguments;
  349. }
  350. if (schemaPart.type === "array") {
  351. if (inArray) {
  352. return 0;
  353. }
  354. if (Array.isArray(schemaPart.items)) {
  355. const i = 0;
  356. for (const item of schemaPart.items) {
  357. addedArguments += traverse(
  358. /** @type {Schema} */
  359. (item),
  360. `${schemaPath}.${i}`,
  361. fullPath,
  362. schemaPath,
  363. `/items/${i}`
  364. );
  365. }
  366. return addedArguments;
  367. }
  368. addedArguments += traverse(
  369. /** @type {Schema} */
  370. (schemaPart.items),
  371. `${schemaPath}[]`,
  372. fullPath,
  373. schemaPath,
  374. "/items"
  375. );
  376. if (addedArguments > 0) {
  377. addResetFlag(fullPath);
  378. addedArguments++;
  379. }
  380. return addedArguments;
  381. }
  382. const ofKey = schemaPart.oneOf
  383. ? "oneOf"
  384. : schemaPart.anyOf
  385. ? "anyOf"
  386. : schemaPart.allOf
  387. ? "allOf"
  388. : undefined;
  389. if (ofKey) {
  390. const items = /** @type {Schema[]} */ (schemaPart[ofKey]);
  391. for (let i = 0; i < items.length; i++) {
  392. addedArguments += traverse(
  393. /** @type {Schema} */
  394. (items[i]),
  395. schemaPath,
  396. fullPath,
  397. inArray,
  398. `/${ofKey}/${i}`
  399. );
  400. }
  401. return addedArguments;
  402. }
  403. return addedArguments;
  404. };
  405. traverse(schema);
  406. // Summarize flags
  407. for (const name of Object.keys(flags)) {
  408. /** @type {Argument} */
  409. const argument = flags[name];
  410. argument.description = argument.configs.reduce((desc, { description }) => {
  411. if (!desc) return description;
  412. if (!description) return desc;
  413. if (desc.includes(description)) return desc;
  414. return `${desc} ${description}`;
  415. }, /** @type {string | undefined} */ (undefined));
  416. argument.simpleType =
  417. /** @type {SimpleType} */
  418. (
  419. argument.configs.reduce((t, argConfig) => {
  420. /** @type {SimpleType} */
  421. let type = "string";
  422. switch (argConfig.type) {
  423. case "number":
  424. type = "number";
  425. break;
  426. case "reset":
  427. case "boolean":
  428. type = "boolean";
  429. break;
  430. case "enum": {
  431. const values =
  432. /** @type {NonNullable<ArgumentConfig["values"]>} */
  433. (argConfig.values);
  434. if (values.every((v) => typeof v === "boolean")) type = "boolean";
  435. if (values.every((v) => typeof v === "number")) type = "number";
  436. break;
  437. }
  438. }
  439. if (t === undefined) return type;
  440. return t === type ? t : "string";
  441. }, /** @type {SimpleType | undefined} */ (undefined))
  442. );
  443. argument.multiple = argument.configs.some((c) => c.multiple);
  444. }
  445. return flags;
  446. };
  447. /** @type {WeakMap<EXPECTED_OBJECT, number>} */
  448. const cliAddedItems = new WeakMap();
  449. /** @typedef {string | number} Property */
  450. /**
  451. * Whether a path segment would walk into the prototype chain.
  452. * @param {string} name path segment
  453. * @returns {boolean} true when the segment is unsafe to write through
  454. */
  455. const isUnsafeKey = (name) =>
  456. name === "__proto__" || name === "constructor" || name === "prototype";
  457. /**
  458. * Gets object and property.
  459. * @param {ObjectConfiguration} config configuration
  460. * @param {string} schemaPath path in the config
  461. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  462. * @returns {{ problem?: LocalProblem, object?: ObjectConfiguration, property?: Property, value?: EXPECTED_OBJECT | EXPECTED_ANY[] }} problem or object with property and value
  463. */
  464. const getObjectAndProperty = (config, schemaPath, index = 0) => {
  465. if (!schemaPath) return { value: config };
  466. const parts = schemaPath.split(".");
  467. const property = /** @type {string} */ (parts.pop());
  468. let current = config;
  469. let i = 0;
  470. for (const part of parts) {
  471. const isArray = part.endsWith("[]");
  472. const name = isArray ? part.slice(0, -2) : part;
  473. if (isUnsafeKey(name)) {
  474. return {
  475. problem: {
  476. type: "prototype-pollution-in-path",
  477. path: parts.slice(0, i).join(".")
  478. }
  479. };
  480. }
  481. let value = current[name];
  482. if (isArray) {
  483. if (value === undefined) {
  484. value = {};
  485. current[name] = [...Array.from({ length: index }), value];
  486. cliAddedItems.set(current[name], index + 1);
  487. } else if (!Array.isArray(value)) {
  488. return {
  489. problem: {
  490. type: "unexpected-non-array-in-path",
  491. path: parts.slice(0, i).join(".")
  492. }
  493. };
  494. } else {
  495. let addedItems = cliAddedItems.get(value) || 0;
  496. while (addedItems <= index) {
  497. value.push(undefined);
  498. addedItems++;
  499. }
  500. cliAddedItems.set(value, addedItems);
  501. const x = value.length - addedItems + index;
  502. if (value[x] === undefined) {
  503. value[x] = {};
  504. } else if (value[x] === null || typeof value[x] !== "object") {
  505. return {
  506. problem: {
  507. type: "unexpected-non-object-in-path",
  508. path: parts.slice(0, i).join(".")
  509. }
  510. };
  511. }
  512. value = value[x];
  513. }
  514. } else if (value === undefined) {
  515. value = current[name] = {};
  516. } else if (value === null || typeof value !== "object") {
  517. return {
  518. problem: {
  519. type: "unexpected-non-object-in-path",
  520. path: parts.slice(0, i).join(".")
  521. }
  522. };
  523. }
  524. current = value;
  525. i++;
  526. }
  527. if (isUnsafeKey(property.endsWith("[]") ? property.slice(0, -2) : property)) {
  528. return {
  529. problem: {
  530. type: "prototype-pollution-in-path",
  531. path: parts.join(".")
  532. }
  533. };
  534. }
  535. const value = current[property];
  536. if (property.endsWith("[]")) {
  537. const name = property.slice(0, -2);
  538. const value = current[name];
  539. if (value === undefined) {
  540. current[name] = [...Array.from({ length: index }), undefined];
  541. cliAddedItems.set(current[name], index + 1);
  542. return { object: current[name], property: index, value: undefined };
  543. } else if (!Array.isArray(value)) {
  544. current[name] = [value, ...Array.from({ length: index }), undefined];
  545. cliAddedItems.set(current[name], index + 1);
  546. return { object: current[name], property: index + 1, value: undefined };
  547. }
  548. let addedItems = cliAddedItems.get(value) || 0;
  549. while (addedItems <= index) {
  550. value.push(undefined);
  551. addedItems++;
  552. }
  553. cliAddedItems.set(value, addedItems);
  554. const x = value.length - addedItems + index;
  555. if (value[x] === undefined) {
  556. value[x] = {};
  557. } else if (value[x] === null || typeof value[x] !== "object") {
  558. return {
  559. problem: {
  560. type: "unexpected-non-object-in-path",
  561. path: schemaPath
  562. }
  563. };
  564. }
  565. return {
  566. object: value,
  567. property: x,
  568. value: value[x]
  569. };
  570. }
  571. return { object: current, property, value };
  572. };
  573. /**
  574. * Updates value using the provided config.
  575. * @param {ObjectConfiguration} config configuration
  576. * @param {string} schemaPath path in the config
  577. * @param {ParsedValue} value parsed value
  578. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  579. * @returns {LocalProblem | null} problem or null for success
  580. */
  581. const setValue = (config, schemaPath, value, index) => {
  582. const { problem, object, property } = getObjectAndProperty(
  583. config,
  584. schemaPath,
  585. index
  586. );
  587. if (problem) return problem;
  588. /** @type {ObjectConfiguration} */
  589. (object)[/** @type {Property} */ (property)] = value;
  590. return null;
  591. };
  592. /**
  593. * Process argument config.
  594. * @param {ArgumentConfig} argConfig processing instructions
  595. * @param {ObjectConfiguration} config configuration
  596. * @param {Value} value the value
  597. * @param {number | undefined} index the index if multiple values provided
  598. * @returns {LocalProblem | null} a problem if any
  599. */
  600. const processArgumentConfig = (argConfig, config, value, index) => {
  601. if (index !== undefined && !argConfig.multiple) {
  602. return {
  603. type: "multiple-values-unexpected",
  604. path: argConfig.path
  605. };
  606. }
  607. const parsed = parseValueForArgumentConfig(argConfig, value);
  608. if (parsed === undefined) {
  609. return {
  610. type: "invalid-value",
  611. path: argConfig.path,
  612. expected: getExpectedValue(argConfig)
  613. };
  614. }
  615. const problem = setValue(config, argConfig.path, parsed, index);
  616. if (problem) return problem;
  617. return null;
  618. };
  619. /**
  620. * Gets expected value.
  621. * @param {ArgumentConfig} argConfig processing instructions
  622. * @returns {string | undefined} expected message
  623. */
  624. const getExpectedValue = (argConfig) => {
  625. switch (argConfig.type) {
  626. case "boolean":
  627. return "true | false";
  628. case "RegExp":
  629. return "regular expression (example: /ab?c*/)";
  630. case "enum":
  631. return /** @type {NonNullable<ArgumentConfig["values"]>} */ (
  632. argConfig.values
  633. )
  634. .map((v) => `${v}`)
  635. .join(" | ");
  636. case "reset":
  637. return "true (will reset the previous value to an empty array)";
  638. default:
  639. return argConfig.type;
  640. }
  641. };
  642. /** @typedef {null | string | number | boolean | RegExp | EnumValue | []} ParsedValue */
  643. const DECIMAL_NUMBER_REGEXP = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
  644. /**
  645. * Parses value for argument config.
  646. * @param {ArgumentConfig} argConfig processing instructions
  647. * @param {Value} value the value
  648. * @returns {ParsedValue | undefined} parsed value
  649. */
  650. const parseValueForArgumentConfig = (argConfig, value) => {
  651. switch (argConfig.type) {
  652. case "string":
  653. if (typeof value === "string") {
  654. return value;
  655. }
  656. break;
  657. case "path":
  658. if (typeof value === "string") {
  659. return path.resolve(value);
  660. }
  661. break;
  662. case "number":
  663. if (typeof value === "number") return value;
  664. if (typeof value === "string" && DECIMAL_NUMBER_REGEXP.test(value)) {
  665. const n = Number(value);
  666. if (!Number.isNaN(n)) return n;
  667. }
  668. break;
  669. case "boolean":
  670. if (typeof value === "boolean") return value;
  671. if (value === "true") return true;
  672. if (value === "false") return false;
  673. break;
  674. case "RegExp":
  675. if (value instanceof RegExp) return value;
  676. if (typeof value === "string") {
  677. // cspell:word yugi
  678. const match = /^\/(.*)\/([yugi]*)$/.exec(value);
  679. if (match && !/[^\\]\//.test(match[1])) {
  680. return new RegExp(match[1], match[2]);
  681. }
  682. }
  683. break;
  684. case "enum": {
  685. const values =
  686. /** @type {EnumValue[]} */
  687. (argConfig.values);
  688. if (values.includes(/** @type {Exclude<Value, RegExp>} */ (value))) {
  689. return value;
  690. }
  691. for (const item of values) {
  692. if (`${item}` === value) return item;
  693. }
  694. break;
  695. }
  696. case "reset":
  697. if (value === true) return [];
  698. break;
  699. }
  700. };
  701. /** @typedef {Record<string, Value[]>} Values */
  702. /**
  703. * Processes the provided arg.
  704. * @param {Flags} args object of arguments
  705. * @param {ObjectConfiguration} config configuration
  706. * @param {Values} values object with values
  707. * @returns {Problem[] | null} problems or null for success
  708. */
  709. const processArguments = (args, config, values) => {
  710. /** @type {Problem[]} */
  711. const problems = [];
  712. for (const key of Object.keys(values)) {
  713. const arg = args[key];
  714. if (!arg) {
  715. problems.push({
  716. type: "unknown-argument",
  717. path: "",
  718. argument: key
  719. });
  720. continue;
  721. }
  722. /**
  723. * Processes the provided value.
  724. * @param {Value} value value
  725. * @param {number | undefined} i index
  726. */
  727. const processValue = (value, i) => {
  728. /** @type {Problem[]} */
  729. const currentProblems = [];
  730. for (const argConfig of arg.configs) {
  731. const problem = processArgumentConfig(argConfig, config, value, i);
  732. if (!problem) {
  733. return;
  734. }
  735. currentProblems.push({
  736. ...problem,
  737. argument: key,
  738. value,
  739. index: i
  740. });
  741. }
  742. problems.push(...currentProblems);
  743. };
  744. const value = values[key];
  745. if (Array.isArray(value)) {
  746. for (let i = 0; i < value.length; i++) {
  747. processValue(value[i], i);
  748. }
  749. } else {
  750. processValue(value, undefined);
  751. }
  752. }
  753. if (problems.length === 0) return null;
  754. return problems;
  755. };
  756. /**
  757. * Checks whether this object is color supported.
  758. * @returns {boolean} true when colors supported, otherwise false
  759. */
  760. const isColorSupported = () => {
  761. const { env = {}, argv = [], platform = "" } = process;
  762. // Read values instead of using `in`: Deno's and Bun's `process.env` honor
  763. // property access but not the `in`/`has` trap, so `"X" in env` is unreliable.
  764. const isDisabled = env.NO_COLOR !== undefined || argv.includes("--no-color");
  765. const isForced = env.FORCE_COLOR !== undefined || argv.includes("--color");
  766. const isWindows = platform === "win32";
  767. const isDumbTerminal = env.TERM === "dumb";
  768. const isCompatibleTerminal = tty.isatty(1) && env.TERM && !isDumbTerminal;
  769. const isCI =
  770. env.CI !== undefined &&
  771. (env.GITHUB_ACTIONS !== undefined ||
  772. env.GITLAB_CI !== undefined ||
  773. env.CIRCLECI !== undefined);
  774. return (
  775. !isDisabled &&
  776. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
  777. );
  778. };
  779. /**
  780. * Returns result.
  781. * @param {number} index index
  782. * @param {string} string string
  783. * @param {string} close close
  784. * @param {string=} replace replace
  785. * @param {string=} head head
  786. * @param {string=} tail tail
  787. * @param {number=} next next
  788. * @returns {string} result
  789. */
  790. const replaceClose = (
  791. index,
  792. string,
  793. close,
  794. replace,
  795. head = string.slice(0, Math.max(0, index)) + replace,
  796. tail = string.slice(Math.max(0, index + close.length)),
  797. next = tail.indexOf(close)
  798. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  799. /**
  800. * Returns result.
  801. * @param {number} index index to replace
  802. * @param {string} string string
  803. * @param {string} open open string
  804. * @param {string} close close string
  805. * @param {string=} replace extra replace
  806. * @returns {string} result
  807. */
  808. const clearBleed = (index, string, open, close, replace) =>
  809. index < 0
  810. ? open + string + close
  811. : open + replaceClose(index, string, close, replace) + close;
  812. /** @typedef {(value: EXPECTED_ANY) => string} PrintFunction */
  813. /**
  814. * Returns function to create color.
  815. * @param {string} open open string
  816. * @param {string} close close string
  817. * @param {string=} replace extra replace
  818. * @param {number=} at at
  819. * @returns {PrintFunction} function to create color
  820. */
  821. const filterEmpty =
  822. (open, close, replace = open, at = open.length + 1) =>
  823. (string) =>
  824. string || !(string === "" || string === undefined)
  825. ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace)
  826. : "";
  827. /**
  828. * Returns result.
  829. * @param {number} open open code
  830. * @param {number} close close code
  831. * @param {string=} replace extra replace
  832. * @returns {PrintFunction} result
  833. */
  834. const init = (open, close, replace) =>
  835. filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
  836. /**
  837. * Defines the colors type used by this module.
  838. * @typedef {{ reset: PrintFunction, bold: PrintFunction, dim: PrintFunction, italic: PrintFunction, underline: PrintFunction, inverse: PrintFunction, hidden: PrintFunction, strikethrough: PrintFunction, black: PrintFunction, red: PrintFunction, green: PrintFunction, yellow: PrintFunction, blue: PrintFunction, magenta: PrintFunction, cyan: PrintFunction, white: PrintFunction, gray: PrintFunction, bgBlack: PrintFunction, bgRed: PrintFunction, bgGreen: PrintFunction, bgYellow: PrintFunction, bgBlue: PrintFunction, bgMagenta: PrintFunction, bgCyan: PrintFunction, bgWhite: PrintFunction, blackBright: PrintFunction, redBright: PrintFunction, greenBright: PrintFunction, yellowBright: PrintFunction, blueBright: PrintFunction, magentaBright: PrintFunction, cyanBright: PrintFunction, whiteBright: PrintFunction, bgBlackBright: PrintFunction, bgRedBright: PrintFunction, bgGreenBright: PrintFunction, bgYellowBright: PrintFunction, bgBlueBright: PrintFunction, bgMagentaBright: PrintFunction, bgCyanBright: PrintFunction, bgWhiteBright: PrintFunction }} Colors
  839. */
  840. /**
  841. * Defines the colors options type used by this module.
  842. * @typedef {object} ColorsOptions
  843. * @property {boolean=} useColor force use colors
  844. */
  845. /**
  846. * Creates a colors from the provided colors option.
  847. * @param {ColorsOptions=} options options
  848. * @returns {Colors} colors
  849. */
  850. const createColors = ({ useColor = isColorSupported() } = {}) => ({
  851. reset: useColor ? init(0, 0) : String,
  852. bold: useColor ? init(1, 22, "\u001B[22m\u001B[1m") : String,
  853. dim: useColor ? init(2, 22, "\u001B[22m\u001B[2m") : String,
  854. italic: useColor ? init(3, 23) : String,
  855. underline: useColor ? init(4, 24) : String,
  856. inverse: useColor ? init(7, 27) : String,
  857. hidden: useColor ? init(8, 28) : String,
  858. strikethrough: useColor ? init(9, 29) : String,
  859. black: useColor ? init(30, 39) : String,
  860. red: useColor ? init(31, 39) : String,
  861. green: useColor ? init(32, 39) : String,
  862. yellow: useColor ? init(33, 39) : String,
  863. blue: useColor ? init(34, 39) : String,
  864. magenta: useColor ? init(35, 39) : String,
  865. cyan: useColor ? init(36, 39) : String,
  866. white: useColor ? init(37, 39) : String,
  867. gray: useColor ? init(90, 39) : String,
  868. bgBlack: useColor ? init(40, 49) : String,
  869. bgRed: useColor ? init(41, 49) : String,
  870. bgGreen: useColor ? init(42, 49) : String,
  871. bgYellow: useColor ? init(43, 49) : String,
  872. bgBlue: useColor ? init(44, 49) : String,
  873. bgMagenta: useColor ? init(45, 49) : String,
  874. bgCyan: useColor ? init(46, 49) : String,
  875. bgWhite: useColor ? init(47, 49) : String,
  876. blackBright: useColor ? init(90, 39) : String,
  877. redBright: useColor ? init(91, 39) : String,
  878. greenBright: useColor ? init(92, 39) : String,
  879. yellowBright: useColor ? init(93, 39) : String,
  880. blueBright: useColor ? init(94, 39) : String,
  881. magentaBright: useColor ? init(95, 39) : String,
  882. cyanBright: useColor ? init(96, 39) : String,
  883. whiteBright: useColor ? init(97, 39) : String,
  884. bgBlackBright: useColor ? init(100, 49) : String,
  885. bgRedBright: useColor ? init(101, 49) : String,
  886. bgGreenBright: useColor ? init(102, 49) : String,
  887. bgYellowBright: useColor ? init(103, 49) : String,
  888. bgBlueBright: useColor ? init(104, 49) : String,
  889. bgMagentaBright: useColor ? init(105, 49) : String,
  890. bgCyanBright: useColor ? init(106, 49) : String,
  891. bgWhiteBright: useColor ? init(107, 49) : String
  892. });
  893. module.exports.createColors = createColors;
  894. module.exports.getArguments = getArguments;
  895. module.exports.isColorSupported = isColorSupported;
  896. module.exports.processArguments = processArguments;