index.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. 'use strict';
  2. const ansiStyles = require('ansi-styles');
  3. const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
  4. const {
  5. stringReplaceAll,
  6. stringEncaseCRLFWithFirstIndex
  7. } = require('./util');
  8. const {isArray} = Array;
  9. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  10. const levelMapping = [
  11. 'ansi',
  12. 'ansi',
  13. 'ansi256',
  14. 'ansi16m'
  15. ];
  16. const styles = Object.create(null);
  17. const applyOptions = (object, options = {}) => {
  18. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  19. throw new Error('The `level` option should be an integer from 0 to 3');
  20. }
  21. // Detect level if not set manually
  22. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  23. object.level = options.level === undefined ? colorLevel : options.level;
  24. };
  25. class ChalkClass {
  26. constructor(options) {
  27. // eslint-disable-next-line no-constructor-return
  28. return chalkFactory(options);
  29. }
  30. }
  31. const chalkFactory = options => {
  32. const chalk = {};
  33. applyOptions(chalk, options);
  34. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  35. Object.setPrototypeOf(chalk, Chalk.prototype);
  36. Object.setPrototypeOf(chalk.template, chalk);
  37. chalk.template.constructor = () => {
  38. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  39. };
  40. chalk.template.Instance = ChalkClass;
  41. return chalk.template;
  42. };
  43. function Chalk(options) {
  44. return chalkFactory(options);
  45. }
  46. for (const [styleName, style] of Object.entries(ansiStyles)) {
  47. styles[styleName] = {
  48. get() {
  49. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  50. Object.defineProperty(this, styleName, {value: builder});
  51. return builder;
  52. }
  53. };
  54. }
  55. styles.visible = {
  56. get() {
  57. const builder = createBuilder(this, this._styler, true);
  58. Object.defineProperty(this, 'visible', {value: builder});
  59. return builder;
  60. }
  61. };
  62. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  63. for (const model of usedModels) {
  64. styles[model] = {
  65. get() {
  66. const {level} = this;
  67. return function (...arguments_) {
  68. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  69. return createBuilder(this, styler, this._isEmpty);
  70. };
  71. }
  72. };
  73. }
  74. for (const model of usedModels) {
  75. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  76. styles[bgModel] = {
  77. get() {
  78. const {level} = this;
  79. return function (...arguments_) {
  80. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  81. return createBuilder(this, styler, this._isEmpty);
  82. };
  83. }
  84. };
  85. }
  86. const proto = Object.defineProperties(() => {}, {
  87. ...styles,
  88. level: {
  89. enumerable: true,
  90. get() {
  91. return this._generator.level;
  92. },
  93. set(level) {
  94. this._generator.level = level;
  95. }
  96. }
  97. });
  98. const createStyler = (open, close, parent) => {
  99. let openAll;
  100. let closeAll;
  101. if (parent === undefined) {
  102. openAll = open;
  103. closeAll = close;
  104. } else {
  105. openAll = parent.openAll + open;
  106. closeAll = close + parent.closeAll;
  107. }
  108. return {
  109. open,
  110. close,
  111. openAll,
  112. closeAll,
  113. parent
  114. };
  115. };
  116. const createBuilder = (self, _styler, _isEmpty) => {
  117. const builder = (...arguments_) => {
  118. if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
  119. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  120. return applyStyle(builder, chalkTag(builder, ...arguments_));
  121. }
  122. // Single argument is hot path, implicit coercion is faster than anything
  123. // eslint-disable-next-line no-implicit-coercion
  124. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  125. };
  126. // We alter the prototype because we must return a function, but there is
  127. // no way to create a function with a different prototype
  128. Object.setPrototypeOf(builder, proto);
  129. builder._generator = self;
  130. builder._styler = _styler;
  131. builder._isEmpty = _isEmpty;
  132. return builder;
  133. };
  134. const applyStyle = (self, string) => {
  135. if (self.level <= 0 || !string) {
  136. return self._isEmpty ? '' : string;
  137. }
  138. let styler = self._styler;
  139. if (styler === undefined) {
  140. return string;
  141. }
  142. const {openAll, closeAll} = styler;
  143. if (string.indexOf('\u001B') !== -1) {
  144. while (styler !== undefined) {
  145. // Replace any instances already present with a re-opening code
  146. // otherwise only the part of the string until said closing code
  147. // will be colored, and the rest will simply be 'plain'.
  148. string = stringReplaceAll(string, styler.close, styler.open);
  149. styler = styler.parent;
  150. }
  151. }
  152. // We can move both next actions out of loop, because remaining actions in loop won't have
  153. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  154. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  155. const lfIndex = string.indexOf('\n');
  156. if (lfIndex !== -1) {
  157. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  158. }
  159. return openAll + string + closeAll;
  160. };
  161. let template;
  162. const chalkTag = (chalk, ...strings) => {
  163. const [firstString] = strings;
  164. if (!isArray(firstString) || !isArray(firstString.raw)) {
  165. // If chalk() was called by itself or with a string,
  166. // return the string itself as a string.
  167. return strings.join(' ');
  168. }
  169. const arguments_ = strings.slice(1);
  170. const parts = [firstString.raw[0]];
  171. for (let i = 1; i < firstString.length; i++) {
  172. parts.push(
  173. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  174. String(firstString.raw[i])
  175. );
  176. }
  177. if (template === undefined) {
  178. template = require('./templates');
  179. }
  180. return template(chalk, parts.join(''));
  181. };
  182. Object.defineProperties(Chalk.prototype, styles);
  183. const chalk = Chalk(); // eslint-disable-line new-cap
  184. chalk.supportsColor = stdoutColor;
  185. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  186. chalk.stderr.supportsColor = stderrColor;
  187. module.exports = chalk;