cli.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. const cliAddedItems = new WeakMap();
  373. /** @typedef {string | number} Property */
  374. /**
  375. * @param {ObjectConfiguration} config configuration
  376. * @param {string} schemaPath path in the config
  377. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  378. * @returns {{ problem?: LocalProblem, object?: ObjectConfiguration, property?: Property, value?: EXPECTED_OBJECT | EXPECTED_ANY[] }} problem or object with property and value
  379. */
  380. const getObjectAndProperty = (config, schemaPath, index = 0) => {
  381. if (!schemaPath) return { value: config };
  382. const parts = schemaPath.split(".");
  383. const property = /** @type {string} */ (parts.pop());
  384. let current = config;
  385. let i = 0;
  386. for (const part of parts) {
  387. const isArray = part.endsWith("[]");
  388. const name = isArray ? part.slice(0, -2) : part;
  389. let value = current[name];
  390. if (isArray) {
  391. if (value === undefined) {
  392. value = {};
  393. current[name] = [...Array.from({ length: index }), value];
  394. cliAddedItems.set(current[name], index + 1);
  395. } else if (!Array.isArray(value)) {
  396. return {
  397. problem: {
  398. type: "unexpected-non-array-in-path",
  399. path: parts.slice(0, i).join(".")
  400. }
  401. };
  402. } else {
  403. let addedItems = cliAddedItems.get(value) || 0;
  404. while (addedItems <= index) {
  405. value.push(undefined);
  406. addedItems++;
  407. }
  408. cliAddedItems.set(value, addedItems);
  409. const x = value.length - addedItems + index;
  410. if (value[x] === undefined) {
  411. value[x] = {};
  412. } else if (value[x] === null || typeof value[x] !== "object") {
  413. return {
  414. problem: {
  415. type: "unexpected-non-object-in-path",
  416. path: parts.slice(0, i).join(".")
  417. }
  418. };
  419. }
  420. value = value[x];
  421. }
  422. } else if (value === undefined) {
  423. value = current[name] = {};
  424. } else if (value === null || typeof value !== "object") {
  425. return {
  426. problem: {
  427. type: "unexpected-non-object-in-path",
  428. path: parts.slice(0, i).join(".")
  429. }
  430. };
  431. }
  432. current = value;
  433. i++;
  434. }
  435. const value = current[property];
  436. if (property.endsWith("[]")) {
  437. const name = property.slice(0, -2);
  438. const value = current[name];
  439. if (value === undefined) {
  440. current[name] = [...Array.from({ length: index }), undefined];
  441. cliAddedItems.set(current[name], index + 1);
  442. return { object: current[name], property: index, value: undefined };
  443. } else if (!Array.isArray(value)) {
  444. current[name] = [value, ...Array.from({ length: index }), undefined];
  445. cliAddedItems.set(current[name], index + 1);
  446. return { object: current[name], property: index + 1, value: undefined };
  447. }
  448. let addedItems = cliAddedItems.get(value) || 0;
  449. while (addedItems <= index) {
  450. value.push(undefined);
  451. addedItems++;
  452. }
  453. cliAddedItems.set(value, addedItems);
  454. const x = value.length - addedItems + index;
  455. if (value[x] === undefined) {
  456. value[x] = {};
  457. } else if (value[x] === null || typeof value[x] !== "object") {
  458. return {
  459. problem: {
  460. type: "unexpected-non-object-in-path",
  461. path: schemaPath
  462. }
  463. };
  464. }
  465. return {
  466. object: value,
  467. property: x,
  468. value: value[x]
  469. };
  470. }
  471. return { object: current, property, value };
  472. };
  473. /**
  474. * @param {ObjectConfiguration} config configuration
  475. * @param {string} schemaPath path in the config
  476. * @param {ParsedValue} value parsed value
  477. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  478. * @returns {LocalProblem | null} problem or null for success
  479. */
  480. const setValue = (config, schemaPath, value, index) => {
  481. const { problem, object, property } = getObjectAndProperty(
  482. config,
  483. schemaPath,
  484. index
  485. );
  486. if (problem) return problem;
  487. /** @type {ObjectConfiguration} */
  488. (object)[/** @type {Property} */ (property)] = value;
  489. return null;
  490. };
  491. /**
  492. * @param {ArgumentConfig} argConfig processing instructions
  493. * @param {ObjectConfiguration} config configuration
  494. * @param {Value} value the value
  495. * @param {number | undefined} index the index if multiple values provided
  496. * @returns {LocalProblem | null} a problem if any
  497. */
  498. const processArgumentConfig = (argConfig, config, value, index) => {
  499. if (index !== undefined && !argConfig.multiple) {
  500. return {
  501. type: "multiple-values-unexpected",
  502. path: argConfig.path
  503. };
  504. }
  505. const parsed = parseValueForArgumentConfig(argConfig, value);
  506. if (parsed === undefined) {
  507. return {
  508. type: "invalid-value",
  509. path: argConfig.path,
  510. expected: getExpectedValue(argConfig)
  511. };
  512. }
  513. const problem = setValue(config, argConfig.path, parsed, index);
  514. if (problem) return problem;
  515. return null;
  516. };
  517. /**
  518. * @param {ArgumentConfig} argConfig processing instructions
  519. * @returns {string | undefined} expected message
  520. */
  521. const getExpectedValue = (argConfig) => {
  522. switch (argConfig.type) {
  523. case "boolean":
  524. return "true | false";
  525. case "RegExp":
  526. return "regular expression (example: /ab?c*/)";
  527. case "enum":
  528. return /** @type {NonNullable<ArgumentConfig["values"]>} */ (
  529. argConfig.values
  530. )
  531. .map((v) => `${v}`)
  532. .join(" | ");
  533. case "reset":
  534. return "true (will reset the previous value to an empty array)";
  535. default:
  536. return argConfig.type;
  537. }
  538. };
  539. /** @typedef {null | string | number | boolean | RegExp | EnumValue | []} ParsedValue */
  540. /**
  541. * @param {ArgumentConfig} argConfig processing instructions
  542. * @param {Value} value the value
  543. * @returns {ParsedValue | undefined} parsed value
  544. */
  545. const parseValueForArgumentConfig = (argConfig, value) => {
  546. switch (argConfig.type) {
  547. case "string":
  548. if (typeof value === "string") {
  549. return value;
  550. }
  551. break;
  552. case "path":
  553. if (typeof value === "string") {
  554. return path.resolve(value);
  555. }
  556. break;
  557. case "number":
  558. if (typeof value === "number") return value;
  559. if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) {
  560. const n = Number(value);
  561. if (!Number.isNaN(n)) return n;
  562. }
  563. break;
  564. case "boolean":
  565. if (typeof value === "boolean") return value;
  566. if (value === "true") return true;
  567. if (value === "false") return false;
  568. break;
  569. case "RegExp":
  570. if (value instanceof RegExp) return value;
  571. if (typeof value === "string") {
  572. // cspell:word yugi
  573. const match = /^\/(.*)\/([yugi]*)$/.exec(value);
  574. if (match && !/[^\\]\//.test(match[1])) {
  575. return new RegExp(match[1], match[2]);
  576. }
  577. }
  578. break;
  579. case "enum": {
  580. const values =
  581. /** @type {EnumValue[]} */
  582. (argConfig.values);
  583. if (values.includes(/** @type {Exclude<Value, RegExp>} */ (value))) {
  584. return value;
  585. }
  586. for (const item of values) {
  587. if (`${item}` === value) return item;
  588. }
  589. break;
  590. }
  591. case "reset":
  592. if (value === true) return [];
  593. break;
  594. }
  595. };
  596. /** @typedef {Record<string, Value[]>} Values */
  597. /**
  598. * @param {Flags} args object of arguments
  599. * @param {ObjectConfiguration} config configuration
  600. * @param {Values} values object with values
  601. * @returns {Problem[] | null} problems or null for success
  602. */
  603. const processArguments = (args, config, values) => {
  604. /** @type {Problem[]} */
  605. const problems = [];
  606. for (const key of Object.keys(values)) {
  607. const arg = args[key];
  608. if (!arg) {
  609. problems.push({
  610. type: "unknown-argument",
  611. path: "",
  612. argument: key
  613. });
  614. continue;
  615. }
  616. /**
  617. * @param {Value} value value
  618. * @param {number | undefined} i index
  619. */
  620. const processValue = (value, i) => {
  621. const currentProblems = [];
  622. for (const argConfig of arg.configs) {
  623. const problem = processArgumentConfig(argConfig, config, value, i);
  624. if (!problem) {
  625. return;
  626. }
  627. currentProblems.push({
  628. ...problem,
  629. argument: key,
  630. value,
  631. index: i
  632. });
  633. }
  634. problems.push(...currentProblems);
  635. };
  636. const value = values[key];
  637. if (Array.isArray(value)) {
  638. for (let i = 0; i < value.length; i++) {
  639. processValue(value[i], i);
  640. }
  641. } else {
  642. processValue(value, undefined);
  643. }
  644. }
  645. if (problems.length === 0) return null;
  646. return problems;
  647. };
  648. /**
  649. * @returns {boolean} true when colors supported, otherwise false
  650. */
  651. const isColorSupported = () => {
  652. const { env = {}, argv = [], platform = "" } = process;
  653. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  654. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  655. const isWindows = platform === "win32";
  656. const isDumbTerminal = env.TERM === "dumb";
  657. const isCompatibleTerminal = tty.isatty(1) && env.TERM && !isDumbTerminal;
  658. const isCI =
  659. "CI" in env &&
  660. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  661. return (
  662. !isDisabled &&
  663. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
  664. );
  665. };
  666. /**
  667. * @param {number} index index
  668. * @param {string} string string
  669. * @param {string} close close
  670. * @param {string=} replace replace
  671. * @param {string=} head head
  672. * @param {string=} tail tail
  673. * @param {number=} next next
  674. * @returns {string} result
  675. */
  676. const replaceClose = (
  677. index,
  678. string,
  679. close,
  680. replace,
  681. head = string.slice(0, Math.max(0, index)) + replace,
  682. tail = string.slice(Math.max(0, index + close.length)),
  683. next = tail.indexOf(close)
  684. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  685. /**
  686. * @param {number} index index to replace
  687. * @param {string} string string
  688. * @param {string} open open string
  689. * @param {string} close close string
  690. * @param {string=} replace extra replace
  691. * @returns {string} result
  692. */
  693. const clearBleed = (index, string, open, close, replace) =>
  694. index < 0
  695. ? open + string + close
  696. : open + replaceClose(index, string, close, replace) + close;
  697. /** @typedef {(value: EXPECTED_ANY) => string} PrintFunction */
  698. /**
  699. * @param {string} open open string
  700. * @param {string} close close string
  701. * @param {string=} replace extra replace
  702. * @param {number=} at at
  703. * @returns {PrintFunction} function to create color
  704. */
  705. const filterEmpty =
  706. (open, close, replace = open, at = open.length + 1) =>
  707. (string) =>
  708. string || !(string === "" || string === undefined)
  709. ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace)
  710. : "";
  711. /**
  712. * @param {number} open open code
  713. * @param {number} close close code
  714. * @param {string=} replace extra replace
  715. * @returns {PrintFunction} result
  716. */
  717. const init = (open, close, replace) =>
  718. filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
  719. /**
  720. * @typedef {{
  721. * reset: PrintFunction
  722. * bold: PrintFunction
  723. * dim: PrintFunction
  724. * italic: PrintFunction
  725. * underline: PrintFunction
  726. * inverse: PrintFunction
  727. * hidden: PrintFunction
  728. * strikethrough: PrintFunction
  729. * black: PrintFunction
  730. * red: PrintFunction
  731. * green: PrintFunction
  732. * yellow: PrintFunction
  733. * blue: PrintFunction
  734. * magenta: PrintFunction
  735. * cyan: PrintFunction
  736. * white: PrintFunction
  737. * gray: PrintFunction
  738. * bgBlack: PrintFunction
  739. * bgRed: PrintFunction
  740. * bgGreen: PrintFunction
  741. * bgYellow: PrintFunction
  742. * bgBlue: PrintFunction
  743. * bgMagenta: PrintFunction
  744. * bgCyan: PrintFunction
  745. * bgWhite: PrintFunction
  746. * blackBright: PrintFunction
  747. * redBright: PrintFunction
  748. * greenBright: PrintFunction
  749. * yellowBright: PrintFunction
  750. * blueBright: PrintFunction
  751. * magentaBright: PrintFunction
  752. * cyanBright: PrintFunction
  753. * whiteBright: PrintFunction
  754. * bgBlackBright: PrintFunction
  755. * bgRedBright: PrintFunction
  756. * bgGreenBright: PrintFunction
  757. * bgYellowBright: PrintFunction
  758. * bgBlueBright: PrintFunction
  759. * bgMagentaBright: PrintFunction
  760. * bgCyanBright: PrintFunction
  761. * bgWhiteBright: PrintFunction
  762. }} Colors */
  763. /**
  764. * @typedef {object} ColorsOptions
  765. * @property {boolean=} useColor force use colors
  766. */
  767. /**
  768. * @param {ColorsOptions=} options options
  769. * @returns {Colors} colors
  770. */
  771. const createColors = ({ useColor = isColorSupported() } = {}) => ({
  772. reset: useColor ? init(0, 0) : String,
  773. bold: useColor ? init(1, 22, "\u001B[22m\u001B[1m") : String,
  774. dim: useColor ? init(2, 22, "\u001B[22m\u001B[2m") : String,
  775. italic: useColor ? init(3, 23) : String,
  776. underline: useColor ? init(4, 24) : String,
  777. inverse: useColor ? init(7, 27) : String,
  778. hidden: useColor ? init(8, 28) : String,
  779. strikethrough: useColor ? init(9, 29) : String,
  780. black: useColor ? init(30, 39) : String,
  781. red: useColor ? init(31, 39) : String,
  782. green: useColor ? init(32, 39) : String,
  783. yellow: useColor ? init(33, 39) : String,
  784. blue: useColor ? init(34, 39) : String,
  785. magenta: useColor ? init(35, 39) : String,
  786. cyan: useColor ? init(36, 39) : String,
  787. white: useColor ? init(37, 39) : String,
  788. gray: useColor ? init(90, 39) : String,
  789. bgBlack: useColor ? init(40, 49) : String,
  790. bgRed: useColor ? init(41, 49) : String,
  791. bgGreen: useColor ? init(42, 49) : String,
  792. bgYellow: useColor ? init(43, 49) : String,
  793. bgBlue: useColor ? init(44, 49) : String,
  794. bgMagenta: useColor ? init(45, 49) : String,
  795. bgCyan: useColor ? init(46, 49) : String,
  796. bgWhite: useColor ? init(47, 49) : String,
  797. blackBright: useColor ? init(90, 39) : String,
  798. redBright: useColor ? init(91, 39) : String,
  799. greenBright: useColor ? init(92, 39) : String,
  800. yellowBright: useColor ? init(93, 39) : String,
  801. blueBright: useColor ? init(94, 39) : String,
  802. magentaBright: useColor ? init(95, 39) : String,
  803. cyanBright: useColor ? init(96, 39) : String,
  804. whiteBright: useColor ? init(97, 39) : String,
  805. bgBlackBright: useColor ? init(100, 49) : String,
  806. bgRedBright: useColor ? init(101, 49) : String,
  807. bgGreenBright: useColor ? init(102, 49) : String,
  808. bgYellowBright: useColor ? init(103, 49) : String,
  809. bgBlueBright: useColor ? init(104, 49) : String,
  810. bgMagentaBright: useColor ? init(105, 49) : String,
  811. bgCyanBright: useColor ? init(106, 49) : String,
  812. bgWhiteBright: useColor ? init(107, 49) : String
  813. });
  814. module.exports.createColors = createColors;
  815. module.exports.getArguments = getArguments;
  816. module.exports.isColorSupported = isColorSupported;
  817. module.exports.processArguments = processArguments;