cli.js 24 KB

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