UNPKG

6.25 kBJavaScriptView Raw
1'use strict';
2const escapeStringRegexp = require('escape-string-regexp');
3const ansiStyles = require('ansi-styles');
4const supportsColor = require('supports-color');
5
6const template = require('./templates.js');
7
8const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
9
10// `supportsColor.level` → `ansiStyles.color[name]` mapping
11const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
12
13// `color-convert` models to exclude from the Chalk API due to conflicts and such
14const skipModels = new Set(['gray']);
15
16const styles = Object.create(null);
17
18function applyOptions(obj, options) {
19 options = options || {};
20
21 // Detect level if not set manually
22 const scLevel = supportsColor ? supportsColor.level : 0;
23 obj.level = options.level === undefined ? scLevel : options.level;
24 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
25}
26
27function Chalk(options) {
28 // We check for this.template here since calling `chalk.constructor()`
29 // by itself will have a `this` of a previously constructed chalk object
30 if (!this || !(this instanceof Chalk) || this.template) {
31 const chalk = {};
32 applyOptions(chalk, options);
33
34 chalk.template = function () {
35 const args = [].slice.call(arguments);
36 return chalkTag.apply(null, [chalk.template].concat(args));
37 };
38
39 Object.setPrototypeOf(chalk, Chalk.prototype);
40 Object.setPrototypeOf(chalk.template, chalk);
41
42 chalk.template.constructor = Chalk;
43
44 return chalk.template;
45 }
46
47 applyOptions(this, options);
48}
49
50// Use bright blue on Windows as the normal blue color is illegible
51if (isSimpleWindowsTerm) {
52 ansiStyles.blue.open = '\u001B[94m';
53}
54
55for (const key of Object.keys(ansiStyles)) {
56 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
57
58 styles[key] = {
59 get() {
60 const codes = ansiStyles[key];
61 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
62 }
63 };
64}
65
66ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
67for (const model of Object.keys(ansiStyles.color.ansi)) {
68 if (skipModels.has(model)) {
69 continue;
70 }
71
72 styles[model] = {
73 get() {
74 const level = this.level;
75 return function () {
76 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
77 const codes = {
78 open,
79 close: ansiStyles.color.close,
80 closeRe: ansiStyles.color.closeRe
81 };
82 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
83 };
84 }
85 };
86}
87
88ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
89for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
90 if (skipModels.has(model)) {
91 continue;
92 }
93
94 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
95 styles[bgModel] = {
96 get() {
97 const level = this.level;
98 return function () {
99 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
100 const codes = {
101 open,
102 close: ansiStyles.bgColor.close,
103 closeRe: ansiStyles.bgColor.closeRe
104 };
105 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
106 };
107 }
108 };
109}
110
111const proto = Object.defineProperties(() => {}, styles);
112
113function build(_styles, key) {
114 const builder = function () {
115 return applyStyle.apply(builder, arguments);
116 };
117
118 builder._styles = _styles;
119
120 const self = this;
121
122 Object.defineProperty(builder, 'level', {
123 enumerable: true,
124 get() {
125 return self.level;
126 },
127 set(level) {
128 self.level = level;
129 }
130 });
131
132 Object.defineProperty(builder, 'enabled', {
133 enumerable: true,
134 get() {
135 return self.enabled;
136 },
137 set(enabled) {
138 self.enabled = enabled;
139 }
140 });
141
142 // See below for fix regarding invisible grey/dim combination on Windows
143 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
144
145 // `__proto__` is used because we must return a function, but there is
146 // no way to create a function with a different prototype
147 builder.__proto__ = proto; // eslint-disable-line no-proto
148
149 return builder;
150}
151
152function applyStyle() {
153 // Support varags, but simply cast to string in case there's only one arg
154 const args = arguments;
155 const argsLen = args.length;
156 let str = String(arguments[0]);
157
158 if (argsLen === 0) {
159 return '';
160 }
161
162 if (argsLen > 1) {
163 // Don't slice `arguments`, it prevents V8 optimizations
164 for (let a = 1; a < argsLen; a++) {
165 str += ' ' + args[a];
166 }
167 }
168
169 if (!this.enabled || this.level <= 0 || !str) {
170 return str;
171 }
172
173 // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
174 // see https://github.com/chalk/chalk/issues/58
175 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
176 const originalDim = ansiStyles.dim.open;
177 if (isSimpleWindowsTerm && this.hasGrey) {
178 ansiStyles.dim.open = '';
179 }
180
181 for (const code of this._styles.slice().reverse()) {
182 // Replace any instances already present with a re-opening code
183 // otherwise only the part of the string until said closing code
184 // will be colored, and the rest will simply be 'plain'.
185 str = code.open + str.replace(code.closeRe, code.open) + code.close;
186
187 // Close the styling before a linebreak and reopen
188 // after next line to fix a bleed issue on macOS
189 // https://github.com/chalk/chalk/pull/92
190 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
191 }
192
193 // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
194 ansiStyles.dim.open = originalDim;
195
196 return str;
197}
198
199function chalkTag(chalk, strings) {
200 if (!Array.isArray(strings)) {
201 // If chalk() was called by itself or with a string,
202 // return the string itself as a string.
203 return [].slice.call(arguments, 1).join(' ');
204 }
205
206 const args = [].slice.call(arguments, 2);
207 const parts = [strings.raw[0]];
208
209 for (let i = 1; i < strings.length; i++) {
210 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
211 parts.push(String(strings.raw[i]));
212 }
213
214 return template(chalk, parts.join(''));
215}
216
217Object.defineProperties(Chalk.prototype, styles);
218
219module.exports = Chalk(); // eslint-disable-line new-cap
220module.exports.supportsColor = supportsColor;
221module.exports.default = module.exports; // For TypeScript