Compare commits
71 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa06bb5ac3 | ||
|
|
51557784b8 | ||
|
|
5c91505e18 | ||
|
|
a8f5bf7a67 | ||
|
|
67db246ae0 | ||
|
|
79ee2d386c | ||
|
|
5dbc1e2633 | ||
|
|
4ebb62d1ca | ||
|
|
fc809b686d | ||
|
|
83acfcf8cb | ||
|
|
f8381204fb | ||
|
|
4a10354857 | ||
|
|
77126fba13 | ||
|
|
795273f17a | ||
|
|
386909ee0b | ||
|
|
2db3c7701e | ||
|
|
f7b29ae8ef | ||
|
|
f399cd0ff6 | ||
|
|
72c742d471 | ||
|
|
5aafc0af74 | ||
|
|
df0e69df51 | ||
|
|
29b856959f | ||
|
|
a370f468a4 | ||
|
|
7443e9faa0 | ||
|
|
a027e3c1e0 | ||
|
|
79c56dfc1e | ||
|
|
c3d14f9ea8 | ||
|
|
158bf4429e | ||
|
|
a34bcf6327 | ||
|
|
1b4cd21fb1 | ||
|
|
6e0df055f4 | ||
|
|
92c55db46f | ||
|
|
d7d75717b3 | ||
|
|
96f44c976b | ||
|
|
c2311622c3 | ||
|
|
ba5c385ecf | ||
|
|
503b9d35cd | ||
|
|
b17d862944 | ||
|
|
d28690e66b | ||
|
|
bccde97f8a | ||
|
|
85f7e96f75 | ||
|
|
4d5c4795ad | ||
|
|
7a6893551d | ||
|
|
04fdbd6d8d | ||
|
|
d7c4aac07e | ||
|
|
09fd5c4ba8 | ||
|
|
c987c61486 | ||
|
|
f478655c3c | ||
|
|
3761e455a1 | ||
|
|
95217429be | ||
|
|
625a285772 | ||
|
|
48d25d156a | ||
|
|
b68c8b5102 | ||
|
|
f8a3642a81 | ||
|
|
4cf2e40e07 | ||
|
|
0fba91b037 | ||
|
|
d798222a5a | ||
|
|
fa16f4ec37 | ||
|
|
4dab5e1fb6 | ||
|
|
9bf298571e | ||
|
|
2a9abb18f4 | ||
|
|
97a0861848 | ||
|
|
0433fcff2a | ||
|
|
d5fb377019 | ||
|
|
ca330532ec | ||
|
|
e304e8c230 | ||
|
|
02abeebac3 | ||
|
|
72299f99a0 | ||
|
|
c0d8e7ed8a | ||
|
|
b31d6fb48a | ||
|
|
445092f9af |
33 changed files with 1466 additions and 1182 deletions
3
.github/funding.yml
vendored
3
.github/funding.yml
vendored
|
|
@ -1,5 +1,4 @@
|
|||
github: sindresorhus
|
||||
github: [sindresorhus, Qix-]
|
||||
open_collective: sindresorhus
|
||||
patreon: sindresorhus
|
||||
tidelift: npm/chalk
|
||||
custom: https://sindresorhus.com/donate
|
||||
|
|
|
|||
26
.github/workflows/main.yml
vendored
Normal file
26
.github/workflows/main.yml
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
name: CI
|
||||
on:
|
||||
- push
|
||||
- pull_request
|
||||
jobs:
|
||||
test:
|
||||
name: Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version:
|
||||
- 18
|
||||
- 16
|
||||
- 14
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- run: npm install
|
||||
- run: npm test
|
||||
- uses: codecov/codecov-action@v2
|
||||
if: matrix.node-version == 16
|
||||
with:
|
||||
fail_ci_if_error: true
|
||||
2
.replit
2
.replit
|
|
@ -1,2 +0,0 @@
|
|||
language = "nodejs"
|
||||
run = "cd examples && node rainbow"
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
language: node_js
|
||||
node_js:
|
||||
- '12'
|
||||
- '10'
|
||||
after_success:
|
||||
- './node_modules/.bin/nyc report --reporter=text-lcov | ./node_modules/.bin/coveralls'
|
||||
|
|
@ -1,10 +1,7 @@
|
|||
/* globals suite, set, bench */
|
||||
'use strict';
|
||||
const chalk = require('.');
|
||||
/* globals suite, bench */
|
||||
import chalk from './index.js';
|
||||
|
||||
suite('chalk', () => {
|
||||
set('iterations', 1000000);
|
||||
|
||||
const chalkRed = chalk.red;
|
||||
const chalkBgRed = chalk.bgRed;
|
||||
const chalkBlueBgRed = chalk.blue.bgRed;
|
||||
|
|
@ -48,8 +45,6 @@ suite('chalk', () => {
|
|||
chalkBgRed(blueStyledString);
|
||||
});
|
||||
|
||||
set('iterations', 10000);
|
||||
|
||||
bench('cached: 1 style template literal', () => {
|
||||
// eslint-disable-next-line no-unused-expressions
|
||||
chalkRed`the fox jumps over the lazy dog`;
|
||||
|
|
|
|||
|
|
@ -1,24 +1,24 @@
|
|||
'use strict';
|
||||
const chalk = require('..');
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import convertColor from 'color-convert';
|
||||
import updateLog from 'log-update';
|
||||
import chalk from '../source/index.js';
|
||||
|
||||
const ignoreChars = /[^!-~]/g;
|
||||
|
||||
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
|
||||
|
||||
function rainbow(string, offset) {
|
||||
if (!string || string.length === 0) {
|
||||
return string;
|
||||
}
|
||||
|
||||
const hueStep = 360 / string.replace(ignoreChars, '').length;
|
||||
const hueStep = 360 / string.replaceAll(ignoreChars, '').length;
|
||||
|
||||
let hue = offset % 360;
|
||||
const characters = [];
|
||||
for (const character of string) {
|
||||
if (character.match(ignoreChars)) {
|
||||
if (ignoreChars.test(character)) {
|
||||
characters.push(character);
|
||||
} else {
|
||||
characters.push(chalk.hsl(hue, 100, 50)(character));
|
||||
characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character));
|
||||
hue = (hue + hueStep) % 360;
|
||||
}
|
||||
}
|
||||
|
|
@ -27,15 +27,12 @@ function rainbow(string, offset) {
|
|||
}
|
||||
|
||||
async function animateString(string) {
|
||||
console.log();
|
||||
for (let i = 0; i < 360 * 5; i++) {
|
||||
console.log('\u001B[1F\u001B[G', rainbow(string, i));
|
||||
for (let index = 0; index < 360 * 5; index++) {
|
||||
updateLog(rainbow(string, index));
|
||||
await delay(2); // eslint-disable-line no-await-in-loop
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
console.log();
|
||||
await animateString('We hope you enjoy Chalk! <3');
|
||||
console.log();
|
||||
})();
|
||||
console.log();
|
||||
await animateString('We hope you enjoy Chalk! <3');
|
||||
console.log();
|
||||
|
|
|
|||
|
|
@ -1,12 +1,21 @@
|
|||
'use strict';
|
||||
const styles = require('ansi-styles');
|
||||
const chalk = require('..');
|
||||
import process from 'node:process';
|
||||
import styles from 'ansi-styles';
|
||||
import chalk from '../source/index.js';
|
||||
|
||||
// Generates screenshot
|
||||
for (const key of Object.keys(styles)) {
|
||||
let returnValue = key;
|
||||
|
||||
if (key === 'reset' || key === 'hidden' || key === 'grey') {
|
||||
// We skip `overline` as almost no terminal supports it so we cannot show it off.
|
||||
if (
|
||||
key === 'reset'
|
||||
|| key === 'hidden'
|
||||
|| key === 'grey'
|
||||
|| key === 'bgGray'
|
||||
|| key === 'bgGrey'
|
||||
|| key === 'overline'
|
||||
|| key.endsWith('Bright')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
|||
415
index.d.ts
vendored
415
index.d.ts
vendored
|
|
@ -1,415 +0,0 @@
|
|||
/**
|
||||
Basic foreground colors.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
declare type ForegroundColor =
|
||||
| 'black'
|
||||
| 'red'
|
||||
| 'green'
|
||||
| 'yellow'
|
||||
| 'blue'
|
||||
| 'magenta'
|
||||
| 'cyan'
|
||||
| 'white'
|
||||
| 'gray'
|
||||
| 'grey'
|
||||
| 'blackBright'
|
||||
| 'redBright'
|
||||
| 'greenBright'
|
||||
| 'yellowBright'
|
||||
| 'blueBright'
|
||||
| 'magentaBright'
|
||||
| 'cyanBright'
|
||||
| 'whiteBright';
|
||||
|
||||
/**
|
||||
Basic background colors.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
declare type BackgroundColor =
|
||||
| 'bgBlack'
|
||||
| 'bgRed'
|
||||
| 'bgGreen'
|
||||
| 'bgYellow'
|
||||
| 'bgBlue'
|
||||
| 'bgMagenta'
|
||||
| 'bgCyan'
|
||||
| 'bgWhite'
|
||||
| 'bgGray'
|
||||
| 'bgGrey'
|
||||
| 'bgBlackBright'
|
||||
| 'bgRedBright'
|
||||
| 'bgGreenBright'
|
||||
| 'bgYellowBright'
|
||||
| 'bgBlueBright'
|
||||
| 'bgMagentaBright'
|
||||
| 'bgCyanBright'
|
||||
| 'bgWhiteBright';
|
||||
|
||||
/**
|
||||
Basic colors.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
declare type Color = ForegroundColor | BackgroundColor;
|
||||
|
||||
declare type Modifiers =
|
||||
| 'reset'
|
||||
| 'bold'
|
||||
| 'dim'
|
||||
| 'italic'
|
||||
| 'underline'
|
||||
| 'inverse'
|
||||
| 'hidden'
|
||||
| 'strikethrough'
|
||||
| 'visible';
|
||||
|
||||
declare namespace chalk {
|
||||
/**
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
type Level = 0 | 1 | 2 | 3;
|
||||
|
||||
interface Options {
|
||||
/**
|
||||
Specify the color support for Chalk.
|
||||
|
||||
By default, color support is automatically detected based on the environment.
|
||||
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
level?: Level;
|
||||
}
|
||||
|
||||
/**
|
||||
Return a new Chalk instance.
|
||||
*/
|
||||
type Instance = new (options?: Options) => Chalk;
|
||||
|
||||
/**
|
||||
Detect whether the terminal supports color.
|
||||
*/
|
||||
interface ColorSupport {
|
||||
/**
|
||||
The color level used by Chalk.
|
||||
*/
|
||||
level: Level;
|
||||
|
||||
/**
|
||||
Return whether Chalk supports basic 16 colors.
|
||||
*/
|
||||
hasBasic: boolean;
|
||||
|
||||
/**
|
||||
Return whether Chalk supports ANSI 256 colors.
|
||||
*/
|
||||
has256: boolean;
|
||||
|
||||
/**
|
||||
Return whether Chalk supports Truecolor 16 million colors.
|
||||
*/
|
||||
has16m: boolean;
|
||||
}
|
||||
|
||||
interface ChalkFunction {
|
||||
/**
|
||||
Use a template string.
|
||||
|
||||
@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
log(chalk`
|
||||
CPU: {red ${cpu.totalPercent}%}
|
||||
RAM: {green ${ram.used / ram.total * 100}%}
|
||||
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
|
||||
`);
|
||||
```
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
|
||||
```
|
||||
*/
|
||||
(text: TemplateStringsArray, ...placeholders: unknown[]): string;
|
||||
|
||||
(...text: unknown[]): string;
|
||||
}
|
||||
|
||||
interface Chalk extends ChalkFunction {
|
||||
/**
|
||||
Return a new Chalk instance.
|
||||
*/
|
||||
Instance: Instance;
|
||||
|
||||
/**
|
||||
The color support for Chalk.
|
||||
|
||||
By default, color support is automatically detected based on the environment.
|
||||
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
level: Level;
|
||||
|
||||
/**
|
||||
Use HEX value to set text color.
|
||||
|
||||
@param color - Hexadecimal value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
chalk.hex('#DEADED');
|
||||
```
|
||||
*/
|
||||
hex(color: string): Chalk;
|
||||
|
||||
/**
|
||||
Use keyword color value to set text color.
|
||||
|
||||
@param color - Keyword value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
chalk.keyword('orange');
|
||||
```
|
||||
*/
|
||||
keyword(color: string): Chalk;
|
||||
|
||||
/**
|
||||
Use RGB values to set text color.
|
||||
*/
|
||||
rgb(red: number, green: number, blue: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HSL values to set text color.
|
||||
*/
|
||||
hsl(hue: number, saturation: number, lightness: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HSV values to set text color.
|
||||
*/
|
||||
hsv(hue: number, saturation: number, value: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HWB values to set text color.
|
||||
*/
|
||||
hwb(hue: number, whiteness: number, blackness: number): Chalk;
|
||||
|
||||
/**
|
||||
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
|
||||
|
||||
30 <= code && code < 38 || 90 <= code && code < 98
|
||||
For example, 31 for red, 91 for redBright.
|
||||
*/
|
||||
ansi(code: number): Chalk;
|
||||
|
||||
/**
|
||||
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
|
||||
*/
|
||||
ansi256(index: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HEX value to set background color.
|
||||
|
||||
@param color - Hexadecimal value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
chalk.bgHex('#DEADED');
|
||||
```
|
||||
*/
|
||||
bgHex(color: string): Chalk;
|
||||
|
||||
/**
|
||||
Use keyword color value to set background color.
|
||||
|
||||
@param color - Keyword value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk = require('chalk');
|
||||
|
||||
chalk.bgKeyword('orange');
|
||||
```
|
||||
*/
|
||||
bgKeyword(color: string): Chalk;
|
||||
|
||||
/**
|
||||
Use RGB values to set background color.
|
||||
*/
|
||||
bgRgb(red: number, green: number, blue: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HSL values to set background color.
|
||||
*/
|
||||
bgHsl(hue: number, saturation: number, lightness: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HSV values to set background color.
|
||||
*/
|
||||
bgHsv(hue: number, saturation: number, value: number): Chalk;
|
||||
|
||||
/**
|
||||
Use HWB values to set background color.
|
||||
*/
|
||||
bgHwb(hue: number, whiteness: number, blackness: number): Chalk;
|
||||
|
||||
/**
|
||||
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
|
||||
|
||||
30 <= code && code < 38 || 90 <= code && code < 98
|
||||
For example, 31 for red, 91 for redBright.
|
||||
Use the foreground code, not the background code (for example, not 41, nor 101).
|
||||
*/
|
||||
bgAnsi(code: number): Chalk;
|
||||
|
||||
/**
|
||||
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
|
||||
*/
|
||||
bgAnsi256(index: number): Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Resets the current color chain.
|
||||
*/
|
||||
readonly reset: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Make text bold.
|
||||
*/
|
||||
readonly bold: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Emitting only a small amount of light.
|
||||
*/
|
||||
readonly dim: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Make text italic. (Not widely supported)
|
||||
*/
|
||||
readonly italic: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Make text underline. (Not widely supported)
|
||||
*/
|
||||
readonly underline: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Inverse background and foreground colors.
|
||||
*/
|
||||
readonly inverse: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Prints the text, but makes it invisible.
|
||||
*/
|
||||
readonly hidden: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
|
||||
*/
|
||||
readonly strikethrough: Chalk;
|
||||
|
||||
/**
|
||||
Modifier: Prints the text only when Chalk has a color support level > 0.
|
||||
Can be useful for things that are purely cosmetic.
|
||||
*/
|
||||
readonly visible: Chalk;
|
||||
|
||||
readonly black: Chalk;
|
||||
readonly red: Chalk;
|
||||
readonly green: Chalk;
|
||||
readonly yellow: Chalk;
|
||||
readonly blue: Chalk;
|
||||
readonly magenta: Chalk;
|
||||
readonly cyan: Chalk;
|
||||
readonly white: Chalk;
|
||||
|
||||
/*
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly gray: Chalk;
|
||||
|
||||
/*
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly grey: Chalk;
|
||||
|
||||
readonly blackBright: Chalk;
|
||||
readonly redBright: Chalk;
|
||||
readonly greenBright: Chalk;
|
||||
readonly yellowBright: Chalk;
|
||||
readonly blueBright: Chalk;
|
||||
readonly magentaBright: Chalk;
|
||||
readonly cyanBright: Chalk;
|
||||
readonly whiteBright: Chalk;
|
||||
|
||||
readonly bgBlack: Chalk;
|
||||
readonly bgRed: Chalk;
|
||||
readonly bgGreen: Chalk;
|
||||
readonly bgYellow: Chalk;
|
||||
readonly bgBlue: Chalk;
|
||||
readonly bgMagenta: Chalk;
|
||||
readonly bgCyan: Chalk;
|
||||
readonly bgWhite: Chalk;
|
||||
|
||||
/*
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGray: Chalk;
|
||||
|
||||
/*
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGrey: Chalk;
|
||||
|
||||
readonly bgBlackBright: Chalk;
|
||||
readonly bgRedBright: Chalk;
|
||||
readonly bgGreenBright: Chalk;
|
||||
readonly bgYellowBright: Chalk;
|
||||
readonly bgBlueBright: Chalk;
|
||||
readonly bgMagentaBright: Chalk;
|
||||
readonly bgCyanBright: Chalk;
|
||||
readonly bgWhiteBright: Chalk;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Main Chalk object that allows to chain styles together.
|
||||
Call the last one as a method with a string argument.
|
||||
Order doesn't matter, and later styles take precedent in case of a conflict.
|
||||
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
|
||||
*/
|
||||
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
|
||||
supportsColor: chalk.ColorSupport | false;
|
||||
Level: chalk.Level;
|
||||
Color: Color;
|
||||
ForegroundColor: ForegroundColor;
|
||||
BackgroundColor: BackgroundColor;
|
||||
Modifiers: Modifiers;
|
||||
stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
|
||||
};
|
||||
|
||||
export = chalk;
|
||||
2
license
2
license
|
|
@ -1,6 +1,6 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
|
|
|||
BIN
media/screenshot.png
Normal file
BIN
media/screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 235 KiB |
61
package.json
61
package.json
|
|
@ -1,21 +1,32 @@
|
|||
{
|
||||
"name": "chalk",
|
||||
"version": "4.1.1",
|
||||
"version": "5.6.2",
|
||||
"description": "Terminal string styling done right",
|
||||
"license": "MIT",
|
||||
"repository": "chalk/chalk",
|
||||
"funding": "https://github.com/chalk/chalk?sponsor=1",
|
||||
"main": "source",
|
||||
"type": "module",
|
||||
"main": "./source/index.js",
|
||||
"exports": "./source/index.js",
|
||||
"imports": {
|
||||
"#ansi-styles": "./source/vendor/ansi-styles/index.js",
|
||||
"#supports-color": {
|
||||
"node": "./source/vendor/supports-color/index.js",
|
||||
"default": "./source/vendor/supports-color/browser.js"
|
||||
}
|
||||
},
|
||||
"types": "./source/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
"node": "^12.17.0 || ^14.13 || >=16.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && nyc ava && tsd",
|
||||
"test": "xo && c8 ava && tsd",
|
||||
"bench": "matcha benchmark.js"
|
||||
},
|
||||
"files": [
|
||||
"source",
|
||||
"index.d.ts"
|
||||
"!source/index.test-d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"color",
|
||||
|
|
@ -25,7 +36,6 @@
|
|||
"console",
|
||||
"cli",
|
||||
"string",
|
||||
"str",
|
||||
"ansi",
|
||||
"style",
|
||||
"styles",
|
||||
|
|
@ -40,29 +50,34 @@
|
|||
"command-line",
|
||||
"text"
|
||||
],
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ava": "^2.4.0",
|
||||
"coveralls": "^3.0.7",
|
||||
"execa": "^4.0.0",
|
||||
"import-fresh": "^3.1.0",
|
||||
"@types/node": "^16.11.10",
|
||||
"ava": "^3.15.0",
|
||||
"c8": "^7.10.0",
|
||||
"color-convert": "^2.0.1",
|
||||
"execa": "^6.0.0",
|
||||
"log-update": "^5.0.0",
|
||||
"matcha": "^0.7.0",
|
||||
"nyc": "^15.0.0",
|
||||
"resolve-from": "^5.0.0",
|
||||
"tsd": "^0.7.4",
|
||||
"xo": "^0.28.2"
|
||||
"tsd": "^0.19.0",
|
||||
"xo": "^0.57.0",
|
||||
"yoctodelay": "^2.0.0"
|
||||
},
|
||||
"xo": {
|
||||
"rules": {
|
||||
"unicorn/prefer-string-slice": "off",
|
||||
"unicorn/prefer-includes": "off",
|
||||
"@typescript-eslint/member-ordering": "off",
|
||||
"no-redeclare": "off",
|
||||
"unicorn/string-content": "off",
|
||||
"unicorn/better-regex": "off"
|
||||
"@typescript-eslint/consistent-type-imports": "off",
|
||||
"@typescript-eslint/consistent-type-exports": "off",
|
||||
"@typescript-eslint/consistent-type-definitions": "off",
|
||||
"unicorn/expiring-todo-comments": "off"
|
||||
}
|
||||
},
|
||||
"c8": {
|
||||
"reporter": [
|
||||
"text",
|
||||
"lcov"
|
||||
],
|
||||
"exclude": [
|
||||
"source/vendor"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
188
readme.md
188
readme.md
|
|
@ -9,74 +9,42 @@
|
|||
|
||||
> Terminal string styling done right
|
||||
|
||||
[](https://travis-ci.org/chalk/chalk) [](https://coveralls.io/github/chalk/chalk?branch=master) [](https://www.npmjs.com/package/chalk?activeTab=dependents) [](https://www.npmjs.com/package/chalk) [](https://www.youtube.com/watch?v=9auOCbH5Ns4) [](https://github.com/xojs/xo)  [](https://repl.it/github/chalk/chalk)
|
||||
[](https://codecov.io/gh/chalk/chalk)
|
||||
[](https://www.npmjs.com/package/chalk?activeTab=dependents)
|
||||
[](https://www.npmjs.com/package/chalk)
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
|
||||

|
||||
|
||||
<br>
|
||||
## Info
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<p>
|
||||
<p>
|
||||
<sup>
|
||||
Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
|
||||
</sup>
|
||||
</p>
|
||||
<sup>Special thanks to:</sup>
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://standardresume.co/tech">
|
||||
<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
|
||||
</a>
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://retool.com/?utm_campaign=sindresorhus">
|
||||
<img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="210"/>
|
||||
</a>
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
|
||||
<div>
|
||||
<img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
|
||||
</div>
|
||||
<b>All your environment variables, in one place</b>
|
||||
<div>
|
||||
<span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
|
||||
<br>
|
||||
<span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
|
||||
</div>
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<br>
|
||||
- [Why not switch to a smaller coloring package?](https://github.com/chalk/chalk?tab=readme-ov-file#why-not-switch-to-a-smaller-coloring-package)
|
||||
- See [yoctocolors](https://github.com/sindresorhus/yoctocolors) for a smaller alternative
|
||||
|
||||
## Highlights
|
||||
|
||||
- Expressive API
|
||||
- Highly performant
|
||||
- No dependencies
|
||||
- Ability to nest styles
|
||||
- [256/Truecolor color support](#256-and-truecolor-color-support)
|
||||
- Auto-detects color support
|
||||
- Doesn't extend `String.prototype`
|
||||
- Clean and focused
|
||||
- Actively maintained
|
||||
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
|
||||
- [Used by ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
$ npm install chalk
|
||||
```sh
|
||||
npm install chalk
|
||||
```
|
||||
|
||||
**IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0)
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
import chalk from 'chalk';
|
||||
|
||||
console.log(chalk.blue('Hello world!'));
|
||||
```
|
||||
|
|
@ -84,7 +52,8 @@ console.log(chalk.blue('Hello world!'));
|
|||
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
import chalk from 'chalk';
|
||||
|
||||
const log = console.log;
|
||||
|
||||
// Combine styled and normal strings
|
||||
|
|
@ -113,15 +82,7 @@ RAM: ${chalk.green('40%')}
|
|||
DISK: ${chalk.yellow('70%')}
|
||||
`);
|
||||
|
||||
// ES2015 tagged template literal
|
||||
log(chalk`
|
||||
CPU: {red ${cpu.totalPercent}%}
|
||||
RAM: {green ${ram.used / ram.total * 100}%}
|
||||
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
|
||||
`);
|
||||
|
||||
// Use RGB colors in terminal emulators that support it.
|
||||
log(chalk.keyword('orange')('Yay for orange colored text!'));
|
||||
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
|
||||
log(chalk.hex('#DEADED').bold('Bold gray!'));
|
||||
```
|
||||
|
|
@ -129,10 +90,10 @@ log(chalk.hex('#DEADED').bold('Bold gray!'));
|
|||
Easily define your own themes:
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
import chalk from 'chalk';
|
||||
|
||||
const error = chalk.bold.red;
|
||||
const warning = chalk.keyword('orange');
|
||||
const warning = chalk.hex('#FFA500'); // Orange color
|
||||
|
||||
console.log(error('Error!'));
|
||||
console.log(warning('Warning!'));
|
||||
|
|
@ -141,6 +102,8 @@ console.log(warning('Warning!'));
|
|||
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
|
||||
|
||||
```js
|
||||
import chalk from 'chalk';
|
||||
|
||||
const name = 'Sindre';
|
||||
console.log(chalk.green('Hello %s'), name);
|
||||
//=> 'Hello Sindre'
|
||||
|
|
@ -165,7 +128,9 @@ Color support is automatically detected, but you can override it by setting the
|
|||
If you need to change this in a reusable module, create a new instance:
|
||||
|
||||
```js
|
||||
const ctx = new chalk.Instance({level: 0});
|
||||
import {Chalk} from 'chalk';
|
||||
|
||||
const customChalk = new Chalk({level: 0});
|
||||
```
|
||||
|
||||
| Level | Description |
|
||||
|
|
@ -175,7 +140,7 @@ const ctx = new chalk.Instance({level: 0});
|
|||
| `2` | 256 color support |
|
||||
| `3` | Truecolor support (16 million colors) |
|
||||
|
||||
### chalk.supportsColor
|
||||
### supportsColor
|
||||
|
||||
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
|
||||
|
||||
|
|
@ -183,23 +148,40 @@ Can be overridden by the user with the flags `--color` and `--no-color`. For sit
|
|||
|
||||
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
|
||||
|
||||
### chalk.stderr and chalk.stderr.supportsColor
|
||||
### chalkStderr and supportsColorStderr
|
||||
|
||||
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
|
||||
`chalkStderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `supportsColor` apply to this too. `supportsColorStderr` is exposed for convenience.
|
||||
|
||||
### modifierNames, foregroundColorNames, backgroundColorNames, and colorNames
|
||||
|
||||
All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`.
|
||||
|
||||
This can be useful if you wrap Chalk and need to validate input:
|
||||
|
||||
```js
|
||||
import {modifierNames, foregroundColorNames} from 'chalk';
|
||||
|
||||
console.log(modifierNames.includes('bold'));
|
||||
//=> true
|
||||
|
||||
console.log(foregroundColorNames.includes('pink'));
|
||||
//=> false
|
||||
```
|
||||
|
||||
## Styles
|
||||
|
||||
### Modifiers
|
||||
|
||||
- `reset` - Resets the current color chain.
|
||||
- `bold` - Make text bold.
|
||||
- `dim` - Emitting only a small amount of light.
|
||||
- `italic` - Make text italic. *(Not widely supported)*
|
||||
- `underline` - Make text underline. *(Not widely supported)*
|
||||
- `inverse`- Inverse background and foreground colors.
|
||||
- `hidden` - Prints the text, but makes it invisible.
|
||||
- `reset` - Reset the current style.
|
||||
- `bold` - Make the text bold.
|
||||
- `dim` - Make the text have lower opacity.
|
||||
- `italic` - Make the text italic. *(Not widely supported)*
|
||||
- `underline` - Put a horizontal line below the text. *(Not widely supported)*
|
||||
- `overline` - Put a horizontal line above the text. *(Not widely supported)*
|
||||
- `inverse` - Invert background and foreground colors.
|
||||
- `hidden` - Print the text but make it invisible.
|
||||
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
|
||||
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
|
||||
- `visible` - Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.
|
||||
|
||||
### Colors
|
||||
|
||||
|
|
@ -239,81 +221,59 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
|
|||
- `bgCyanBright`
|
||||
- `bgWhiteBright`
|
||||
|
||||
## Tagged template literal
|
||||
|
||||
Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
|
||||
|
||||
```js
|
||||
const chalk = require('chalk');
|
||||
|
||||
const miles = 18;
|
||||
const calculateFeet = miles => miles * 5280;
|
||||
|
||||
console.log(chalk`
|
||||
There are {bold 5280 feet} in a mile.
|
||||
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
|
||||
`);
|
||||
```
|
||||
|
||||
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
|
||||
|
||||
Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
|
||||
|
||||
```js
|
||||
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
|
||||
console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
|
||||
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
|
||||
```
|
||||
|
||||
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
|
||||
|
||||
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
|
||||
|
||||
## 256 and Truecolor color support
|
||||
|
||||
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
|
||||
Chalk supports 256 colors and [Truecolor](https://github.com/termstandard/colors) (16 million colors) on supported terminal apps.
|
||||
|
||||
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
|
||||
|
||||
Examples:
|
||||
|
||||
- `chalk.hex('#DEADED').underline('Hello, world!')`
|
||||
- `chalk.keyword('orange')('Some orange text')`
|
||||
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
|
||||
|
||||
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
|
||||
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `hex` for foreground colors and `bgHex` for background colors).
|
||||
|
||||
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
|
||||
- `chalk.bgKeyword('orange')('Some orange text')`
|
||||
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
|
||||
|
||||
The following color models can be used:
|
||||
|
||||
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
|
||||
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
|
||||
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
|
||||
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
|
||||
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
|
||||
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
|
||||
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
|
||||
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
|
||||
|
||||
## Browser support
|
||||
|
||||
Since Chrome 69, ANSI escape codes are natively supported in the developer console.
|
||||
|
||||
## Windows
|
||||
|
||||
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
|
||||
|
||||
## Origin story
|
||||
## FAQ
|
||||
|
||||
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
|
||||
### Why not switch to a smaller coloring package?
|
||||
|
||||
## chalk for enterprise
|
||||
Chalk may be larger, but there is a reason for that. It offers a more user-friendly API, well-documented types, supports millions of colors, and covers edge cases that smaller alternatives miss. Chalk is mature, reliable, and built to last.
|
||||
|
||||
Available as part of the Tidelift Subscription.
|
||||
But beyond the technical aspects, there's something more critical: trust and long-term maintenance. I have been active in open source for over a decade, and I'm committed to keeping Chalk maintained. Smaller packages might seem appealing now, but there's no guarantee they will be around for the long term, or that they won't become malicious over time.
|
||||
|
||||
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
Chalk is also likely already in your dependency tree (since 100K+ packages depend on it), so switching won’t save space—in fact, it might increase it. npm deduplicates dependencies, so multiple Chalk instances turn into one, but adding another package alongside it will increase your overall size.
|
||||
|
||||
If the goal is to clean up the ecosystem, switching away from Chalk won’t even make a dent. The real problem lies with packages that have very deep dependency trees (for example, those including a lot of polyfills). Chalk has no dependencies. It's better to focus on impactful changes rather than minor optimizations.
|
||||
|
||||
If absolute package size is important to you, I also maintain [yoctocolors](https://github.com/sindresorhus/yoctocolors), one of the smallest color packages out there.
|
||||
|
||||
*\- [Sindre](https://github.com/sindresorhus)*
|
||||
|
||||
### But the smaller coloring package has benchmarks showing it is faster
|
||||
|
||||
[Micro-benchmarks are flawed](https://sindresorhus.com/blog/micro-benchmark-fallacy) because they measure performance in unrealistic, isolated scenarios, often giving a distorted view of real-world performance. Don't believe marketing fluff. All the coloring packages are more than fast enough.
|
||||
|
||||
## Related
|
||||
|
||||
- [chalk-template](https://github.com/chalk/chalk-template) - [Tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) support for this module
|
||||
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
|
||||
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
|
||||
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
|
||||
|
|
@ -329,6 +289,8 @@ The maintainers of chalk and thousands of other packages are working with Tideli
|
|||
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
|
||||
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
|
||||
|
||||
*(Not accepting additional entries)*
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
|
|
|
|||
325
source/index.d.ts
vendored
Normal file
325
source/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
// TODO: Make it this when TS suports that.
|
||||
// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles';
|
||||
// import {ColorInfo, ColorSupportLevel} from '#supports-color';
|
||||
import {
|
||||
ModifierName,
|
||||
ForegroundColorName,
|
||||
BackgroundColorName,
|
||||
ColorName,
|
||||
} from './vendor/ansi-styles/index.js';
|
||||
import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js';
|
||||
|
||||
export interface Options {
|
||||
/**
|
||||
Specify the color support for Chalk.
|
||||
|
||||
By default, color support is automatically detected based on the environment.
|
||||
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
readonly level?: ColorSupportLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
Return a new Chalk instance.
|
||||
*/
|
||||
export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention
|
||||
|
||||
export interface ChalkInstance {
|
||||
(...text: unknown[]): string;
|
||||
|
||||
/**
|
||||
The color support for Chalk.
|
||||
|
||||
By default, color support is automatically detected based on the environment.
|
||||
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
level: ColorSupportLevel;
|
||||
|
||||
/**
|
||||
Use RGB values to set text color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.rgb(222, 173, 237);
|
||||
```
|
||||
*/
|
||||
rgb: (red: number, green: number, blue: number) => this;
|
||||
|
||||
/**
|
||||
Use HEX value to set text color.
|
||||
|
||||
@param color - Hexadecimal value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.hex('#DEADED');
|
||||
```
|
||||
*/
|
||||
hex: (color: string) => this;
|
||||
|
||||
/**
|
||||
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.ansi256(201);
|
||||
```
|
||||
*/
|
||||
ansi256: (index: number) => this;
|
||||
|
||||
/**
|
||||
Use RGB values to set background color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.bgRgb(222, 173, 237);
|
||||
```
|
||||
*/
|
||||
bgRgb: (red: number, green: number, blue: number) => this;
|
||||
|
||||
/**
|
||||
Use HEX value to set background color.
|
||||
|
||||
@param color - Hexadecimal value representing the desired color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.bgHex('#DEADED');
|
||||
```
|
||||
*/
|
||||
bgHex: (color: string) => this;
|
||||
|
||||
/**
|
||||
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
|
||||
|
||||
@example
|
||||
```
|
||||
import chalk from 'chalk';
|
||||
|
||||
chalk.bgAnsi256(201);
|
||||
```
|
||||
*/
|
||||
bgAnsi256: (index: number) => this;
|
||||
|
||||
/**
|
||||
Modifier: Reset the current style.
|
||||
*/
|
||||
readonly reset: this;
|
||||
|
||||
/**
|
||||
Modifier: Make the text bold.
|
||||
*/
|
||||
readonly bold: this;
|
||||
|
||||
/**
|
||||
Modifier: Make the text have lower opacity.
|
||||
*/
|
||||
readonly dim: this;
|
||||
|
||||
/**
|
||||
Modifier: Make the text italic. *(Not widely supported)*
|
||||
*/
|
||||
readonly italic: this;
|
||||
|
||||
/**
|
||||
Modifier: Put a horizontal line below the text. *(Not widely supported)*
|
||||
*/
|
||||
readonly underline: this;
|
||||
|
||||
/**
|
||||
Modifier: Put a horizontal line above the text. *(Not widely supported)*
|
||||
*/
|
||||
readonly overline: this;
|
||||
|
||||
/**
|
||||
Modifier: Invert background and foreground colors.
|
||||
*/
|
||||
readonly inverse: this;
|
||||
|
||||
/**
|
||||
Modifier: Print the text but make it invisible.
|
||||
*/
|
||||
readonly hidden: this;
|
||||
|
||||
/**
|
||||
Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)*
|
||||
*/
|
||||
readonly strikethrough: this;
|
||||
|
||||
/**
|
||||
Modifier: Print the text only when Chalk has a color level above zero.
|
||||
|
||||
Can be useful for things that are purely cosmetic.
|
||||
*/
|
||||
readonly visible: this;
|
||||
|
||||
readonly black: this;
|
||||
readonly red: this;
|
||||
readonly green: this;
|
||||
readonly yellow: this;
|
||||
readonly blue: this;
|
||||
readonly magenta: this;
|
||||
readonly cyan: this;
|
||||
readonly white: this;
|
||||
|
||||
/*
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly gray: this;
|
||||
|
||||
/*
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly grey: this;
|
||||
|
||||
readonly blackBright: this;
|
||||
readonly redBright: this;
|
||||
readonly greenBright: this;
|
||||
readonly yellowBright: this;
|
||||
readonly blueBright: this;
|
||||
readonly magentaBright: this;
|
||||
readonly cyanBright: this;
|
||||
readonly whiteBright: this;
|
||||
|
||||
readonly bgBlack: this;
|
||||
readonly bgRed: this;
|
||||
readonly bgGreen: this;
|
||||
readonly bgYellow: this;
|
||||
readonly bgBlue: this;
|
||||
readonly bgMagenta: this;
|
||||
readonly bgCyan: this;
|
||||
readonly bgWhite: this;
|
||||
|
||||
/*
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGray: this;
|
||||
|
||||
/*
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGrey: this;
|
||||
|
||||
readonly bgBlackBright: this;
|
||||
readonly bgRedBright: this;
|
||||
readonly bgGreenBright: this;
|
||||
readonly bgYellowBright: this;
|
||||
readonly bgBlueBright: this;
|
||||
readonly bgMagentaBright: this;
|
||||
readonly bgCyanBright: this;
|
||||
readonly bgWhiteBright: this;
|
||||
}
|
||||
|
||||
/**
|
||||
Main Chalk object that allows to chain styles together.
|
||||
|
||||
Call the last one as a method with a string argument.
|
||||
|
||||
Order doesn't matter, and later styles take precedent in case of a conflict.
|
||||
|
||||
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
|
||||
*/
|
||||
declare const chalk: ChalkInstance;
|
||||
|
||||
export const supportsColor: ColorInfo;
|
||||
|
||||
export const chalkStderr: typeof chalk;
|
||||
export const supportsColorStderr: typeof supportsColor;
|
||||
|
||||
export {
|
||||
ModifierName, ForegroundColorName, BackgroundColorName, ColorName,
|
||||
modifierNames, foregroundColorNames, backgroundColorNames, colorNames,
|
||||
// } from '#ansi-styles';
|
||||
} from './vendor/ansi-styles/index.js';
|
||||
|
||||
export {
|
||||
ColorInfo,
|
||||
ColorSupport,
|
||||
ColorSupportLevel,
|
||||
// } from '#supports-color';
|
||||
} from './vendor/supports-color/index.js';
|
||||
|
||||
// TODO: Remove these aliases in the next major version
|
||||
/**
|
||||
@deprecated Use `ModifierName` instead.
|
||||
|
||||
Basic modifier names.
|
||||
*/
|
||||
export type Modifiers = ModifierName;
|
||||
|
||||
/**
|
||||
@deprecated Use `ForegroundColorName` instead.
|
||||
|
||||
Basic foreground color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type ForegroundColor = ForegroundColorName;
|
||||
|
||||
/**
|
||||
@deprecated Use `BackgroundColorName` instead.
|
||||
|
||||
Basic background color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type BackgroundColor = BackgroundColorName;
|
||||
|
||||
/**
|
||||
@deprecated Use `ColorName` instead.
|
||||
|
||||
Basic color names. The combination of foreground and background color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type Color = ColorName;
|
||||
|
||||
/**
|
||||
@deprecated Use `modifierNames` instead.
|
||||
|
||||
Basic modifier names.
|
||||
*/
|
||||
export const modifiers: readonly Modifiers[];
|
||||
|
||||
/**
|
||||
@deprecated Use `foregroundColorNames` instead.
|
||||
|
||||
Basic foreground color names.
|
||||
*/
|
||||
export const foregroundColors: readonly ForegroundColor[];
|
||||
|
||||
/**
|
||||
@deprecated Use `backgroundColorNames` instead.
|
||||
|
||||
Basic background color names.
|
||||
*/
|
||||
export const backgroundColors: readonly BackgroundColor[];
|
||||
|
||||
/**
|
||||
@deprecated Use `colorNames` instead.
|
||||
|
||||
Basic color names. The combination of foreground and background color names.
|
||||
*/
|
||||
export const colors: readonly Color[];
|
||||
|
||||
export default chalk;
|
||||
166
source/index.js
166
source/index.js
|
|
@ -1,19 +1,22 @@
|
|||
'use strict';
|
||||
const ansiStyles = require('ansi-styles');
|
||||
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
|
||||
const {
|
||||
import ansiStyles from '#ansi-styles';
|
||||
import supportsColor from '#supports-color';
|
||||
import { // eslint-disable-line import/order
|
||||
stringReplaceAll,
|
||||
stringEncaseCRLFWithFirstIndex
|
||||
} = require('./util');
|
||||
stringEncaseCRLFWithFirstIndex,
|
||||
} from './utilities.js';
|
||||
|
||||
const {isArray} = Array;
|
||||
const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
|
||||
|
||||
const GENERATOR = Symbol('GENERATOR');
|
||||
const STYLER = Symbol('STYLER');
|
||||
const IS_EMPTY = Symbol('IS_EMPTY');
|
||||
|
||||
// `supportsColor.level` → `ansiStyles.color[name]` mapping
|
||||
const levelMapping = [
|
||||
'ansi',
|
||||
'ansi',
|
||||
'ansi256',
|
||||
'ansi16m'
|
||||
'ansi16m',
|
||||
];
|
||||
|
||||
const styles = Object.create(null);
|
||||
|
|
@ -28,7 +31,7 @@ const applyOptions = (object, options = {}) => {
|
|||
object.level = options.level === undefined ? colorLevel : options.level;
|
||||
};
|
||||
|
||||
class ChalkClass {
|
||||
export class Chalk {
|
||||
constructor(options) {
|
||||
// eslint-disable-next-line no-constructor-return
|
||||
return chalkFactory(options);
|
||||
|
|
@ -36,69 +39,80 @@ class ChalkClass {
|
|||
}
|
||||
|
||||
const chalkFactory = options => {
|
||||
const chalk = {};
|
||||
const chalk = (...strings) => strings.join(' ');
|
||||
applyOptions(chalk, options);
|
||||
|
||||
chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
|
||||
Object.setPrototypeOf(chalk, createChalk.prototype);
|
||||
|
||||
Object.setPrototypeOf(chalk, Chalk.prototype);
|
||||
Object.setPrototypeOf(chalk.template, chalk);
|
||||
|
||||
chalk.template.constructor = () => {
|
||||
throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
|
||||
};
|
||||
|
||||
chalk.template.Instance = ChalkClass;
|
||||
|
||||
return chalk.template;
|
||||
return chalk;
|
||||
};
|
||||
|
||||
function Chalk(options) {
|
||||
function createChalk(options) {
|
||||
return chalkFactory(options);
|
||||
}
|
||||
|
||||
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
|
||||
|
||||
for (const [styleName, style] of Object.entries(ansiStyles)) {
|
||||
styles[styleName] = {
|
||||
get() {
|
||||
const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
|
||||
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
|
||||
Object.defineProperty(this, styleName, {value: builder});
|
||||
return builder;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
styles.visible = {
|
||||
get() {
|
||||
const builder = createBuilder(this, this._styler, true);
|
||||
const builder = createBuilder(this, this[STYLER], true);
|
||||
Object.defineProperty(this, 'visible', {value: builder});
|
||||
return builder;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
|
||||
const getModelAnsi = (model, level, type, ...arguments_) => {
|
||||
if (model === 'rgb') {
|
||||
if (level === 'ansi16m') {
|
||||
return ansiStyles[type].ansi16m(...arguments_);
|
||||
}
|
||||
|
||||
if (level === 'ansi256') {
|
||||
return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
|
||||
}
|
||||
|
||||
return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
|
||||
}
|
||||
|
||||
if (model === 'hex') {
|
||||
return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
|
||||
}
|
||||
|
||||
return ansiStyles[type][model](...arguments_);
|
||||
};
|
||||
|
||||
const usedModels = ['rgb', 'hex', 'ansi256'];
|
||||
|
||||
for (const model of usedModels) {
|
||||
styles[model] = {
|
||||
get() {
|
||||
const {level} = this;
|
||||
return function (...arguments_) {
|
||||
const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
|
||||
return createBuilder(this, styler, this._isEmpty);
|
||||
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
|
||||
return createBuilder(this, styler, this[IS_EMPTY]);
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
for (const model of usedModels) {
|
||||
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
|
||||
styles[bgModel] = {
|
||||
get() {
|
||||
const {level} = this;
|
||||
return function (...arguments_) {
|
||||
const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
|
||||
return createBuilder(this, styler, this._isEmpty);
|
||||
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
|
||||
return createBuilder(this, styler, this[IS_EMPTY]);
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -107,12 +121,12 @@ const proto = Object.defineProperties(() => {}, {
|
|||
level: {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return this._generator.level;
|
||||
return this[GENERATOR].level;
|
||||
},
|
||||
set(level) {
|
||||
this._generator.level = level;
|
||||
}
|
||||
}
|
||||
this[GENERATOR].level = level;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createStyler = (open, close, parent) => {
|
||||
|
|
@ -131,46 +145,39 @@ const createStyler = (open, close, parent) => {
|
|||
close,
|
||||
openAll,
|
||||
closeAll,
|
||||
parent
|
||||
parent,
|
||||
};
|
||||
};
|
||||
|
||||
const createBuilder = (self, _styler, _isEmpty) => {
|
||||
const builder = (...arguments_) => {
|
||||
if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
|
||||
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
|
||||
return applyStyle(builder, chalkTag(builder, ...arguments_));
|
||||
}
|
||||
|
||||
// Single argument is hot path, implicit coercion is faster than anything
|
||||
// eslint-disable-next-line no-implicit-coercion
|
||||
return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
|
||||
};
|
||||
// Single argument is hot path, implicit coercion is faster than anything
|
||||
// eslint-disable-next-line no-implicit-coercion
|
||||
const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
|
||||
|
||||
// We alter the prototype because we must return a function, but there is
|
||||
// no way to create a function with a different prototype
|
||||
Object.setPrototypeOf(builder, proto);
|
||||
|
||||
builder._generator = self;
|
||||
builder._styler = _styler;
|
||||
builder._isEmpty = _isEmpty;
|
||||
builder[GENERATOR] = self;
|
||||
builder[STYLER] = _styler;
|
||||
builder[IS_EMPTY] = _isEmpty;
|
||||
|
||||
return builder;
|
||||
};
|
||||
|
||||
const applyStyle = (self, string) => {
|
||||
if (self.level <= 0 || !string) {
|
||||
return self._isEmpty ? '' : string;
|
||||
return self[IS_EMPTY] ? '' : string;
|
||||
}
|
||||
|
||||
let styler = self._styler;
|
||||
let styler = self[STYLER];
|
||||
|
||||
if (styler === undefined) {
|
||||
return string;
|
||||
}
|
||||
|
||||
const {openAll, closeAll} = styler;
|
||||
if (string.indexOf('\u001B') !== -1) {
|
||||
if (string.includes('\u001B')) {
|
||||
while (styler !== undefined) {
|
||||
// Replace any instances already present with a re-opening code
|
||||
// otherwise only the part of the string until said closing code
|
||||
|
|
@ -192,38 +199,27 @@ const applyStyle = (self, string) => {
|
|||
return openAll + string + closeAll;
|
||||
};
|
||||
|
||||
let template;
|
||||
const chalkTag = (chalk, ...strings) => {
|
||||
const [firstString] = strings;
|
||||
Object.defineProperties(createChalk.prototype, styles);
|
||||
|
||||
if (!isArray(firstString) || !isArray(firstString.raw)) {
|
||||
// If chalk() was called by itself or with a string,
|
||||
// return the string itself as a string.
|
||||
return strings.join(' ');
|
||||
}
|
||||
const chalk = createChalk();
|
||||
export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});
|
||||
|
||||
const arguments_ = strings.slice(1);
|
||||
const parts = [firstString.raw[0]];
|
||||
export {
|
||||
modifierNames,
|
||||
foregroundColorNames,
|
||||
backgroundColorNames,
|
||||
colorNames,
|
||||
|
||||
for (let i = 1; i < firstString.length; i++) {
|
||||
parts.push(
|
||||
String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
|
||||
String(firstString.raw[i])
|
||||
);
|
||||
}
|
||||
// TODO: Remove these aliases in the next major version
|
||||
modifierNames as modifiers,
|
||||
foregroundColorNames as foregroundColors,
|
||||
backgroundColorNames as backgroundColors,
|
||||
colorNames as colors,
|
||||
} from './vendor/ansi-styles/index.js';
|
||||
|
||||
if (template === undefined) {
|
||||
template = require('./templates');
|
||||
}
|
||||
|
||||
return template(chalk, parts.join(''));
|
||||
export {
|
||||
stdoutColor as supportsColor,
|
||||
stderrColor as supportsColorStderr,
|
||||
};
|
||||
|
||||
Object.defineProperties(Chalk.prototype, styles);
|
||||
|
||||
const chalk = Chalk(); // eslint-disable-line new-cap
|
||||
chalk.supportsColor = stdoutColor;
|
||||
chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
|
||||
chalk.stderr.supportsColor = stderrColor;
|
||||
|
||||
module.exports = chalk;
|
||||
export default chalk;
|
||||
|
|
|
|||
|
|
@ -1,62 +1,64 @@
|
|||
import {expectType, expectError} from 'tsd';
|
||||
import chalk = require('.');
|
||||
|
||||
// - Helpers -
|
||||
type colorReturn = chalk.Chalk & {supportsColor?: never};
|
||||
import {
|
||||
expectType,
|
||||
expectAssignable,
|
||||
expectError,
|
||||
expectDeprecated,
|
||||
} from 'tsd';
|
||||
import chalk, {
|
||||
Chalk,
|
||||
ChalkInstance,
|
||||
ColorInfo,
|
||||
ColorSupport,
|
||||
ColorSupportLevel,
|
||||
chalkStderr,
|
||||
supportsColor,
|
||||
supportsColorStderr,
|
||||
ModifierName,
|
||||
ForegroundColorName,
|
||||
BackgroundColorName,
|
||||
ColorName,
|
||||
Modifiers,
|
||||
} from './index.js';
|
||||
|
||||
// - supportsColor -
|
||||
expectType<chalk.ColorSupport | false>(chalk.supportsColor);
|
||||
if (chalk.supportsColor) {
|
||||
expectType<boolean>(chalk.supportsColor.hasBasic);
|
||||
expectType<boolean>(chalk.supportsColor.has256);
|
||||
expectType<boolean>(chalk.supportsColor.has16m);
|
||||
expectType<ColorInfo>(supportsColor);
|
||||
if (supportsColor) {
|
||||
expectType<ColorSupport>(supportsColor);
|
||||
expectType<ColorSupportLevel>(supportsColor.level);
|
||||
expectType<boolean>(supportsColor.hasBasic);
|
||||
expectType<boolean>(supportsColor.has256);
|
||||
expectType<boolean>(supportsColor.has16m);
|
||||
}
|
||||
|
||||
// - stderr -
|
||||
expectType<chalk.Chalk>(chalk.stderr);
|
||||
expectType<chalk.ColorSupport | false>(chalk.stderr.supportsColor);
|
||||
if (chalk.stderr.supportsColor) {
|
||||
expectType<boolean>(chalk.stderr.supportsColor.hasBasic);
|
||||
expectType<boolean>(chalk.stderr.supportsColor.has256);
|
||||
expectType<boolean>(chalk.stderr.supportsColor.has16m);
|
||||
expectAssignable<ChalkInstance>(chalkStderr);
|
||||
expectType<ColorInfo>(supportsColorStderr);
|
||||
if (supportsColorStderr) {
|
||||
expectType<boolean>(supportsColorStderr.hasBasic);
|
||||
expectType<boolean>(supportsColorStderr.has256);
|
||||
expectType<boolean>(supportsColorStderr.has16m);
|
||||
}
|
||||
|
||||
// -- `stderr` is not a member of the Chalk interface --
|
||||
expectError(chalk.reset.stderr);
|
||||
// -- `supportsColorStderr` is not a member of the Chalk interface --
|
||||
expectError(chalk.reset.supportsColorStderr);
|
||||
|
||||
// -- `supportsColor` is not a member of the Chalk interface --
|
||||
expectError(chalk.reset.supportsColor);
|
||||
|
||||
// - Chalk -
|
||||
// -- Instance --
|
||||
expectType<chalk.Chalk>(new chalk.Instance({level: 1}));
|
||||
expectType<ChalkInstance>(new Chalk({level: 1}));
|
||||
|
||||
// -- Properties --
|
||||
expectType<chalk.Level>(chalk.level);
|
||||
|
||||
// -- Template literal --
|
||||
expectType<string>(chalk``);
|
||||
const name = 'John';
|
||||
expectType<string>(chalk`Hello {bold.red ${name}}`);
|
||||
expectType<string>(chalk`Works with numbers {bold.red ${1}}`);
|
||||
expectType<ColorSupportLevel>(chalk.level);
|
||||
|
||||
// -- Color methods --
|
||||
expectType<colorReturn>(chalk.hex('#DEADED'));
|
||||
expectType<colorReturn>(chalk.keyword('orange'));
|
||||
expectType<colorReturn>(chalk.rgb(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.hsl(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.hsv(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.hwb(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.ansi(30));
|
||||
expectType<colorReturn>(chalk.ansi256(0));
|
||||
expectType<colorReturn>(chalk.bgHex('#DEADED'));
|
||||
expectType<colorReturn>(chalk.bgKeyword('orange'));
|
||||
expectType<colorReturn>(chalk.bgRgb(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.bgHsl(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.bgHsv(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.bgHwb(0, 0, 0));
|
||||
expectType<colorReturn>(chalk.bgAnsi(30));
|
||||
expectType<colorReturn>(chalk.bgAnsi256(0));
|
||||
expectType<ChalkInstance>(chalk.rgb(0, 0, 0));
|
||||
expectType<ChalkInstance>(chalk.hex('#DEADED'));
|
||||
expectType<ChalkInstance>(chalk.ansi256(0));
|
||||
expectType<ChalkInstance>(chalk.bgRgb(0, 0, 0));
|
||||
expectType<ChalkInstance>(chalk.bgHex('#DEADED'));
|
||||
expectType<ChalkInstance>(chalk.bgAnsi256(0));
|
||||
|
||||
// -- Modifiers --
|
||||
expectType<string>(chalk.reset('foo'));
|
||||
|
|
@ -64,6 +66,7 @@ expectType<string>(chalk.bold('foo'));
|
|||
expectType<string>(chalk.dim('foo'));
|
||||
expectType<string>(chalk.italic('foo'));
|
||||
expectType<string>(chalk.underline('foo'));
|
||||
expectType<string>(chalk.overline('foo'));
|
||||
expectType<string>(chalk.inverse('foo'));
|
||||
expectType<string>(chalk.hidden('foo'));
|
||||
expectType<string>(chalk.strikethrough('foo'));
|
||||
|
|
@ -157,6 +160,20 @@ expectType<string>(chalk.underline``);
|
|||
expectType<string>(chalk.red.bgGreen.bold`Hello {italic.blue ${name}}`);
|
||||
expectType<string>(chalk.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`);
|
||||
|
||||
// -- Color types ==
|
||||
expectType<typeof chalk.Color>('red');
|
||||
expectError<typeof chalk.Color>('hotpink');
|
||||
// -- Modifiers types
|
||||
expectAssignable<ModifierName>('strikethrough');
|
||||
expectError<ModifierName>('delete');
|
||||
|
||||
// -- Foreground types
|
||||
expectAssignable<ForegroundColorName>('red');
|
||||
expectError<ForegroundColorName>('pink');
|
||||
|
||||
// -- Background types
|
||||
expectAssignable<BackgroundColorName>('bgRed');
|
||||
expectError<BackgroundColorName>('bgPink');
|
||||
|
||||
// -- Color types --
|
||||
expectAssignable<ColorName>('red');
|
||||
expectAssignable<ColorName>('bgRed');
|
||||
expectError<ColorName>('hotpink');
|
||||
expectError<ColorName>('bgHotpink');
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
'use strict';
|
||||
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
|
||||
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
|
||||
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
|
||||
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
|
||||
|
||||
const ESCAPES = new Map([
|
||||
['n', '\n'],
|
||||
['r', '\r'],
|
||||
['t', '\t'],
|
||||
['b', '\b'],
|
||||
['f', '\f'],
|
||||
['v', '\v'],
|
||||
['0', '\0'],
|
||||
['\\', '\\'],
|
||||
['e', '\u001B'],
|
||||
['a', '\u0007']
|
||||
]);
|
||||
|
||||
function unescape(c) {
|
||||
const u = c[0] === 'u';
|
||||
const bracket = c[1] === '{';
|
||||
|
||||
if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
|
||||
return String.fromCharCode(parseInt(c.slice(1), 16));
|
||||
}
|
||||
|
||||
if (u && bracket) {
|
||||
return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
|
||||
}
|
||||
|
||||
return ESCAPES.get(c) || c;
|
||||
}
|
||||
|
||||
function parseArguments(name, arguments_) {
|
||||
const results = [];
|
||||
const chunks = arguments_.trim().split(/\s*,\s*/g);
|
||||
let matches;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const number = Number(chunk);
|
||||
if (!Number.isNaN(number)) {
|
||||
results.push(number);
|
||||
} else if ((matches = chunk.match(STRING_REGEX))) {
|
||||
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
|
||||
} else {
|
||||
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function parseStyle(style) {
|
||||
STYLE_REGEX.lastIndex = 0;
|
||||
|
||||
const results = [];
|
||||
let matches;
|
||||
|
||||
while ((matches = STYLE_REGEX.exec(style)) !== null) {
|
||||
const name = matches[1];
|
||||
|
||||
if (matches[2]) {
|
||||
const args = parseArguments(name, matches[2]);
|
||||
results.push([name].concat(args));
|
||||
} else {
|
||||
results.push([name]);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function buildStyle(chalk, styles) {
|
||||
const enabled = {};
|
||||
|
||||
for (const layer of styles) {
|
||||
for (const style of layer.styles) {
|
||||
enabled[style[0]] = layer.inverse ? null : style.slice(1);
|
||||
}
|
||||
}
|
||||
|
||||
let current = chalk;
|
||||
for (const [styleName, styles] of Object.entries(enabled)) {
|
||||
if (!Array.isArray(styles)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!(styleName in current)) {
|
||||
throw new Error(`Unknown Chalk style: ${styleName}`);
|
||||
}
|
||||
|
||||
current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
module.exports = (chalk, temporary) => {
|
||||
const styles = [];
|
||||
const chunks = [];
|
||||
let chunk = [];
|
||||
|
||||
// eslint-disable-next-line max-params
|
||||
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
|
||||
if (escapeCharacter) {
|
||||
chunk.push(unescape(escapeCharacter));
|
||||
} else if (style) {
|
||||
const string = chunk.join('');
|
||||
chunk = [];
|
||||
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
|
||||
styles.push({inverse, styles: parseStyle(style)});
|
||||
} else if (close) {
|
||||
if (styles.length === 0) {
|
||||
throw new Error('Found extraneous } in Chalk template literal');
|
||||
}
|
||||
|
||||
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
|
||||
chunk = [];
|
||||
styles.pop();
|
||||
} else {
|
||||
chunk.push(character);
|
||||
}
|
||||
});
|
||||
|
||||
chunks.push(chunk.join(''));
|
||||
|
||||
if (styles.length > 0) {
|
||||
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
|
||||
throw new Error(errMessage);
|
||||
}
|
||||
|
||||
return chunks.join('');
|
||||
};
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
const stringReplaceAll = (string, substring, replacer) => {
|
||||
let index = string.indexOf(substring);
|
||||
if (index === -1) {
|
||||
return string;
|
||||
}
|
||||
|
||||
const substringLength = substring.length;
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
do {
|
||||
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
|
||||
endIndex = index + substringLength;
|
||||
index = string.indexOf(substring, endIndex);
|
||||
} while (index !== -1);
|
||||
|
||||
returnValue += string.substr(endIndex);
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
do {
|
||||
const gotCR = string[index - 1] === '\r';
|
||||
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
|
||||
endIndex = index + 1;
|
||||
index = string.indexOf('\n', endIndex);
|
||||
} while (index !== -1);
|
||||
|
||||
returnValue += string.substr(endIndex);
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
stringReplaceAll,
|
||||
stringEncaseCRLFWithFirstIndex
|
||||
};
|
||||
33
source/utilities.js
Normal file
33
source/utilities.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
|
||||
export function stringReplaceAll(string, substring, replacer) {
|
||||
let index = string.indexOf(substring);
|
||||
if (index === -1) {
|
||||
return string;
|
||||
}
|
||||
|
||||
const substringLength = substring.length;
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
do {
|
||||
returnValue += string.slice(endIndex, index) + substring + replacer;
|
||||
endIndex = index + substringLength;
|
||||
index = string.indexOf(substring, endIndex);
|
||||
} while (index !== -1);
|
||||
|
||||
returnValue += string.slice(endIndex);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
|
||||
let endIndex = 0;
|
||||
let returnValue = '';
|
||||
do {
|
||||
const gotCR = string[index - 1] === '\r';
|
||||
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
|
||||
endIndex = index + 1;
|
||||
index = string.indexOf('\n', endIndex);
|
||||
} while (index !== -1);
|
||||
|
||||
returnValue += string.slice(endIndex);
|
||||
return returnValue;
|
||||
}
|
||||
236
source/vendor/ansi-styles/index.d.ts
vendored
Normal file
236
source/vendor/ansi-styles/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
export interface CSPair { // eslint-disable-line @typescript-eslint/naming-convention
|
||||
/**
|
||||
The ANSI terminal control sequence for starting this style.
|
||||
*/
|
||||
readonly open: string;
|
||||
|
||||
/**
|
||||
The ANSI terminal control sequence for ending this style.
|
||||
*/
|
||||
readonly close: string;
|
||||
}
|
||||
|
||||
export interface ColorBase {
|
||||
/**
|
||||
The ANSI terminal control sequence for ending this color.
|
||||
*/
|
||||
readonly close: string;
|
||||
|
||||
ansi(code: number): string;
|
||||
|
||||
ansi256(code: number): string;
|
||||
|
||||
ansi16m(red: number, green: number, blue: number): string;
|
||||
}
|
||||
|
||||
export interface Modifier {
|
||||
/**
|
||||
Resets the current color chain.
|
||||
*/
|
||||
readonly reset: CSPair;
|
||||
|
||||
/**
|
||||
Make text bold.
|
||||
*/
|
||||
readonly bold: CSPair;
|
||||
|
||||
/**
|
||||
Emitting only a small amount of light.
|
||||
*/
|
||||
readonly dim: CSPair;
|
||||
|
||||
/**
|
||||
Make text italic. (Not widely supported)
|
||||
*/
|
||||
readonly italic: CSPair;
|
||||
|
||||
/**
|
||||
Make text underline. (Not widely supported)
|
||||
*/
|
||||
readonly underline: CSPair;
|
||||
|
||||
/**
|
||||
Make text overline.
|
||||
|
||||
Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.
|
||||
*/
|
||||
readonly overline: CSPair;
|
||||
|
||||
/**
|
||||
Inverse background and foreground colors.
|
||||
*/
|
||||
readonly inverse: CSPair;
|
||||
|
||||
/**
|
||||
Prints the text, but makes it invisible.
|
||||
*/
|
||||
readonly hidden: CSPair;
|
||||
|
||||
/**
|
||||
Puts a horizontal line through the center of the text. (Not widely supported)
|
||||
*/
|
||||
readonly strikethrough: CSPair;
|
||||
}
|
||||
|
||||
export interface ForegroundColor {
|
||||
readonly black: CSPair;
|
||||
readonly red: CSPair;
|
||||
readonly green: CSPair;
|
||||
readonly yellow: CSPair;
|
||||
readonly blue: CSPair;
|
||||
readonly cyan: CSPair;
|
||||
readonly magenta: CSPair;
|
||||
readonly white: CSPair;
|
||||
|
||||
/**
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly gray: CSPair;
|
||||
|
||||
/**
|
||||
Alias for `blackBright`.
|
||||
*/
|
||||
readonly grey: CSPair;
|
||||
|
||||
readonly blackBright: CSPair;
|
||||
readonly redBright: CSPair;
|
||||
readonly greenBright: CSPair;
|
||||
readonly yellowBright: CSPair;
|
||||
readonly blueBright: CSPair;
|
||||
readonly cyanBright: CSPair;
|
||||
readonly magentaBright: CSPair;
|
||||
readonly whiteBright: CSPair;
|
||||
}
|
||||
|
||||
export interface BackgroundColor {
|
||||
readonly bgBlack: CSPair;
|
||||
readonly bgRed: CSPair;
|
||||
readonly bgGreen: CSPair;
|
||||
readonly bgYellow: CSPair;
|
||||
readonly bgBlue: CSPair;
|
||||
readonly bgCyan: CSPair;
|
||||
readonly bgMagenta: CSPair;
|
||||
readonly bgWhite: CSPair;
|
||||
|
||||
/**
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGray: CSPair;
|
||||
|
||||
/**
|
||||
Alias for `bgBlackBright`.
|
||||
*/
|
||||
readonly bgGrey: CSPair;
|
||||
|
||||
readonly bgBlackBright: CSPair;
|
||||
readonly bgRedBright: CSPair;
|
||||
readonly bgGreenBright: CSPair;
|
||||
readonly bgYellowBright: CSPair;
|
||||
readonly bgBlueBright: CSPair;
|
||||
readonly bgCyanBright: CSPair;
|
||||
readonly bgMagentaBright: CSPair;
|
||||
readonly bgWhiteBright: CSPair;
|
||||
}
|
||||
|
||||
export interface ConvertColor {
|
||||
/**
|
||||
Convert from the RGB color space to the ANSI 256 color space.
|
||||
|
||||
@param red - (`0...255`)
|
||||
@param green - (`0...255`)
|
||||
@param blue - (`0...255`)
|
||||
*/
|
||||
rgbToAnsi256(red: number, green: number, blue: number): number;
|
||||
|
||||
/**
|
||||
Convert from the RGB HEX color space to the RGB color space.
|
||||
|
||||
@param hex - A hexadecimal string containing RGB data.
|
||||
*/
|
||||
hexToRgb(hex: string): [red: number, green: number, blue: number];
|
||||
|
||||
/**
|
||||
Convert from the RGB HEX color space to the ANSI 256 color space.
|
||||
|
||||
@param hex - A hexadecimal string containing RGB data.
|
||||
*/
|
||||
hexToAnsi256(hex: string): number;
|
||||
|
||||
/**
|
||||
Convert from the ANSI 256 color space to the ANSI 16 color space.
|
||||
|
||||
@param code - A number representing the ANSI 256 color.
|
||||
*/
|
||||
ansi256ToAnsi(code: number): number;
|
||||
|
||||
/**
|
||||
Convert from the RGB color space to the ANSI 16 color space.
|
||||
|
||||
@param red - (`0...255`)
|
||||
@param green - (`0...255`)
|
||||
@param blue - (`0...255`)
|
||||
*/
|
||||
rgbToAnsi(red: number, green: number, blue: number): number;
|
||||
|
||||
/**
|
||||
Convert from the RGB HEX color space to the ANSI 16 color space.
|
||||
|
||||
@param hex - A hexadecimal string containing RGB data.
|
||||
*/
|
||||
hexToAnsi(hex: string): number;
|
||||
}
|
||||
|
||||
/**
|
||||
Basic modifier names.
|
||||
*/
|
||||
export type ModifierName = keyof Modifier;
|
||||
|
||||
/**
|
||||
Basic foreground color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type ForegroundColorName = keyof ForegroundColor;
|
||||
|
||||
/**
|
||||
Basic background color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type BackgroundColorName = keyof BackgroundColor;
|
||||
|
||||
/**
|
||||
Basic color names. The combination of foreground and background color names.
|
||||
|
||||
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
|
||||
*/
|
||||
export type ColorName = ForegroundColorName | BackgroundColorName;
|
||||
|
||||
/**
|
||||
Basic modifier names.
|
||||
*/
|
||||
export const modifierNames: readonly ModifierName[];
|
||||
|
||||
/**
|
||||
Basic foreground color names.
|
||||
*/
|
||||
export const foregroundColorNames: readonly ForegroundColorName[];
|
||||
|
||||
/**
|
||||
Basic background color names.
|
||||
*/
|
||||
export const backgroundColorNames: readonly BackgroundColorName[];
|
||||
|
||||
/*
|
||||
Basic color names. The combination of foreground and background color names.
|
||||
*/
|
||||
export const colorNames: readonly ColorName[];
|
||||
|
||||
declare const ansiStyles: {
|
||||
readonly modifier: Modifier;
|
||||
readonly color: ColorBase & ForegroundColor;
|
||||
readonly bgColor: ColorBase & BackgroundColor;
|
||||
readonly codes: ReadonlyMap<number, number>;
|
||||
} & ForegroundColor & BackgroundColor & Modifier & ConvertColor;
|
||||
|
||||
export default ansiStyles;
|
||||
223
source/vendor/ansi-styles/index.js
vendored
Normal file
223
source/vendor/ansi-styles/index.js
vendored
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
const ANSI_BACKGROUND_OFFSET = 10;
|
||||
|
||||
const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
|
||||
|
||||
const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
|
||||
|
||||
const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
|
||||
|
||||
const styles = {
|
||||
modifier: {
|
||||
reset: [0, 0],
|
||||
// 21 isn't widely supported and 22 does the same thing
|
||||
bold: [1, 22],
|
||||
dim: [2, 22],
|
||||
italic: [3, 23],
|
||||
underline: [4, 24],
|
||||
overline: [53, 55],
|
||||
inverse: [7, 27],
|
||||
hidden: [8, 28],
|
||||
strikethrough: [9, 29],
|
||||
},
|
||||
color: {
|
||||
black: [30, 39],
|
||||
red: [31, 39],
|
||||
green: [32, 39],
|
||||
yellow: [33, 39],
|
||||
blue: [34, 39],
|
||||
magenta: [35, 39],
|
||||
cyan: [36, 39],
|
||||
white: [37, 39],
|
||||
|
||||
// Bright color
|
||||
blackBright: [90, 39],
|
||||
gray: [90, 39], // Alias of `blackBright`
|
||||
grey: [90, 39], // Alias of `blackBright`
|
||||
redBright: [91, 39],
|
||||
greenBright: [92, 39],
|
||||
yellowBright: [93, 39],
|
||||
blueBright: [94, 39],
|
||||
magentaBright: [95, 39],
|
||||
cyanBright: [96, 39],
|
||||
whiteBright: [97, 39],
|
||||
},
|
||||
bgColor: {
|
||||
bgBlack: [40, 49],
|
||||
bgRed: [41, 49],
|
||||
bgGreen: [42, 49],
|
||||
bgYellow: [43, 49],
|
||||
bgBlue: [44, 49],
|
||||
bgMagenta: [45, 49],
|
||||
bgCyan: [46, 49],
|
||||
bgWhite: [47, 49],
|
||||
|
||||
// Bright color
|
||||
bgBlackBright: [100, 49],
|
||||
bgGray: [100, 49], // Alias of `bgBlackBright`
|
||||
bgGrey: [100, 49], // Alias of `bgBlackBright`
|
||||
bgRedBright: [101, 49],
|
||||
bgGreenBright: [102, 49],
|
||||
bgYellowBright: [103, 49],
|
||||
bgBlueBright: [104, 49],
|
||||
bgMagentaBright: [105, 49],
|
||||
bgCyanBright: [106, 49],
|
||||
bgWhiteBright: [107, 49],
|
||||
},
|
||||
};
|
||||
|
||||
export const modifierNames = Object.keys(styles.modifier);
|
||||
export const foregroundColorNames = Object.keys(styles.color);
|
||||
export const backgroundColorNames = Object.keys(styles.bgColor);
|
||||
export const colorNames = [...foregroundColorNames, ...backgroundColorNames];
|
||||
|
||||
function assembleStyles() {
|
||||
const codes = new Map();
|
||||
|
||||
for (const [groupName, group] of Object.entries(styles)) {
|
||||
for (const [styleName, style] of Object.entries(group)) {
|
||||
styles[styleName] = {
|
||||
open: `\u001B[${style[0]}m`,
|
||||
close: `\u001B[${style[1]}m`,
|
||||
};
|
||||
|
||||
group[styleName] = styles[styleName];
|
||||
|
||||
codes.set(style[0], style[1]);
|
||||
}
|
||||
|
||||
Object.defineProperty(styles, groupName, {
|
||||
value: group,
|
||||
enumerable: false,
|
||||
});
|
||||
}
|
||||
|
||||
Object.defineProperty(styles, 'codes', {
|
||||
value: codes,
|
||||
enumerable: false,
|
||||
});
|
||||
|
||||
styles.color.close = '\u001B[39m';
|
||||
styles.bgColor.close = '\u001B[49m';
|
||||
|
||||
styles.color.ansi = wrapAnsi16();
|
||||
styles.color.ansi256 = wrapAnsi256();
|
||||
styles.color.ansi16m = wrapAnsi16m();
|
||||
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
|
||||
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
|
||||
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
|
||||
|
||||
// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
|
||||
Object.defineProperties(styles, {
|
||||
rgbToAnsi256: {
|
||||
value(red, green, blue) {
|
||||
// We use the extended greyscale palette here, with the exception of
|
||||
// black and white. normal palette only has 4 greyscale shades.
|
||||
if (red === green && green === blue) {
|
||||
if (red < 8) {
|
||||
return 16;
|
||||
}
|
||||
|
||||
if (red > 248) {
|
||||
return 231;
|
||||
}
|
||||
|
||||
return Math.round(((red - 8) / 247) * 24) + 232;
|
||||
}
|
||||
|
||||
return 16
|
||||
+ (36 * Math.round(red / 255 * 5))
|
||||
+ (6 * Math.round(green / 255 * 5))
|
||||
+ Math.round(blue / 255 * 5);
|
||||
},
|
||||
enumerable: false,
|
||||
},
|
||||
hexToRgb: {
|
||||
value(hex) {
|
||||
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
|
||||
if (!matches) {
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
let [colorString] = matches;
|
||||
|
||||
if (colorString.length === 3) {
|
||||
colorString = [...colorString].map(character => character + character).join('');
|
||||
}
|
||||
|
||||
const integer = Number.parseInt(colorString, 16);
|
||||
|
||||
return [
|
||||
/* eslint-disable no-bitwise */
|
||||
(integer >> 16) & 0xFF,
|
||||
(integer >> 8) & 0xFF,
|
||||
integer & 0xFF,
|
||||
/* eslint-enable no-bitwise */
|
||||
];
|
||||
},
|
||||
enumerable: false,
|
||||
},
|
||||
hexToAnsi256: {
|
||||
value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
|
||||
enumerable: false,
|
||||
},
|
||||
ansi256ToAnsi: {
|
||||
value(code) {
|
||||
if (code < 8) {
|
||||
return 30 + code;
|
||||
}
|
||||
|
||||
if (code < 16) {
|
||||
return 90 + (code - 8);
|
||||
}
|
||||
|
||||
let red;
|
||||
let green;
|
||||
let blue;
|
||||
|
||||
if (code >= 232) {
|
||||
red = (((code - 232) * 10) + 8) / 255;
|
||||
green = red;
|
||||
blue = red;
|
||||
} else {
|
||||
code -= 16;
|
||||
|
||||
const remainder = code % 36;
|
||||
|
||||
red = Math.floor(code / 36) / 5;
|
||||
green = Math.floor(remainder / 6) / 5;
|
||||
blue = (remainder % 6) / 5;
|
||||
}
|
||||
|
||||
const value = Math.max(red, green, blue) * 2;
|
||||
|
||||
if (value === 0) {
|
||||
return 30;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-bitwise
|
||||
let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
|
||||
|
||||
if (value === 2) {
|
||||
result += 60;
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
enumerable: false,
|
||||
},
|
||||
rgbToAnsi: {
|
||||
value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
|
||||
enumerable: false,
|
||||
},
|
||||
hexToAnsi: {
|
||||
value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
|
||||
enumerable: false,
|
||||
},
|
||||
});
|
||||
|
||||
return styles;
|
||||
}
|
||||
|
||||
const ansiStyles = assembleStyles();
|
||||
|
||||
export default ansiStyles;
|
||||
1
source/vendor/supports-color/browser.d.ts
vendored
Normal file
1
source/vendor/supports-color/browser.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export {default} from './index.js';
|
||||
34
source/vendor/supports-color/browser.js
vendored
Normal file
34
source/vendor/supports-color/browser.js
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
/* eslint-env browser */
|
||||
|
||||
const level = (() => {
|
||||
if (!('navigator' in globalThis)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (globalThis.navigator.userAgentData) {
|
||||
const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
|
||||
if (brand && brand.version > 93) {
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
})();
|
||||
|
||||
const colorSupport = level !== 0 && {
|
||||
level,
|
||||
hasBasic: true,
|
||||
has256: level >= 2,
|
||||
has16m: level >= 3,
|
||||
};
|
||||
|
||||
const supportsColor = {
|
||||
stdout: colorSupport,
|
||||
stderr: colorSupport,
|
||||
};
|
||||
|
||||
export default supportsColor;
|
||||
55
source/vendor/supports-color/index.d.ts
vendored
Normal file
55
source/vendor/supports-color/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import type {WriteStream} from 'node:tty';
|
||||
|
||||
export type Options = {
|
||||
/**
|
||||
Whether `process.argv` should be sniffed for `--color` and `--no-color` flags.
|
||||
|
||||
@default true
|
||||
*/
|
||||
readonly sniffFlags?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
Levels:
|
||||
- `0` - All colors disabled.
|
||||
- `1` - Basic 16 colors support.
|
||||
- `2` - ANSI 256 colors support.
|
||||
- `3` - Truecolor 16 million colors support.
|
||||
*/
|
||||
export type ColorSupportLevel = 0 | 1 | 2 | 3;
|
||||
|
||||
/**
|
||||
Detect whether the terminal supports color.
|
||||
*/
|
||||
export type ColorSupport = {
|
||||
/**
|
||||
The color level.
|
||||
*/
|
||||
level: ColorSupportLevel;
|
||||
|
||||
/**
|
||||
Whether basic 16 colors are supported.
|
||||
*/
|
||||
hasBasic: boolean;
|
||||
|
||||
/**
|
||||
Whether ANSI 256 colors are supported.
|
||||
*/
|
||||
has256: boolean;
|
||||
|
||||
/**
|
||||
Whether Truecolor 16 million colors are supported.
|
||||
*/
|
||||
has16m: boolean;
|
||||
};
|
||||
|
||||
export type ColorInfo = ColorSupport | false;
|
||||
|
||||
export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo;
|
||||
|
||||
declare const supportsColor: {
|
||||
stdout: ColorInfo;
|
||||
stderr: ColorInfo;
|
||||
};
|
||||
|
||||
export default supportsColor;
|
||||
190
source/vendor/supports-color/index.js
vendored
Normal file
190
source/vendor/supports-color/index.js
vendored
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import process from 'node:process';
|
||||
import os from 'node:os';
|
||||
import tty from 'node:tty';
|
||||
|
||||
// From: https://github.com/sindresorhus/has-flag/blob/main/index.js
|
||||
/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
|
||||
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
|
||||
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
|
||||
const position = argv.indexOf(prefix + flag);
|
||||
const terminatorPosition = argv.indexOf('--');
|
||||
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
|
||||
}
|
||||
|
||||
const {env} = process;
|
||||
|
||||
let flagForceColor;
|
||||
if (
|
||||
hasFlag('no-color')
|
||||
|| hasFlag('no-colors')
|
||||
|| hasFlag('color=false')
|
||||
|| hasFlag('color=never')
|
||||
) {
|
||||
flagForceColor = 0;
|
||||
} else if (
|
||||
hasFlag('color')
|
||||
|| hasFlag('colors')
|
||||
|| hasFlag('color=true')
|
||||
|| hasFlag('color=always')
|
||||
) {
|
||||
flagForceColor = 1;
|
||||
}
|
||||
|
||||
function envForceColor() {
|
||||
if ('FORCE_COLOR' in env) {
|
||||
if (env.FORCE_COLOR === 'true') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (env.FORCE_COLOR === 'false') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
|
||||
}
|
||||
}
|
||||
|
||||
function translateLevel(level) {
|
||||
if (level === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
level,
|
||||
hasBasic: true,
|
||||
has256: level >= 2,
|
||||
has16m: level >= 3,
|
||||
};
|
||||
}
|
||||
|
||||
function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
|
||||
const noFlagForceColor = envForceColor();
|
||||
if (noFlagForceColor !== undefined) {
|
||||
flagForceColor = noFlagForceColor;
|
||||
}
|
||||
|
||||
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
|
||||
|
||||
if (forceColor === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (sniffFlags) {
|
||||
if (hasFlag('color=16m')
|
||||
|| hasFlag('color=full')
|
||||
|| hasFlag('color=truecolor')) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (hasFlag('color=256')) {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for Azure DevOps pipelines.
|
||||
// Has to be above the `!streamIsTTY` check.
|
||||
if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (haveStream && !streamIsTTY && forceColor === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const min = forceColor || 0;
|
||||
|
||||
if (env.TERM === 'dumb') {
|
||||
return min;
|
||||
}
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
|
||||
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
|
||||
const osRelease = os.release().split('.');
|
||||
if (
|
||||
Number(osRelease[0]) >= 10
|
||||
&& Number(osRelease[2]) >= 10_586
|
||||
) {
|
||||
return Number(osRelease[2]) >= 14_931 ? 3 : 2;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ('CI' in env) {
|
||||
if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
if ('TEAMCITY_VERSION' in env) {
|
||||
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
|
||||
}
|
||||
|
||||
if (env.COLORTERM === 'truecolor') {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (env.TERM === 'xterm-kitty') {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (env.TERM === 'xterm-ghostty') {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (env.TERM === 'wezterm') {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if ('TERM_PROGRAM' in env) {
|
||||
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
|
||||
|
||||
switch (env.TERM_PROGRAM) {
|
||||
case 'iTerm.app': {
|
||||
return version >= 3 ? 3 : 2;
|
||||
}
|
||||
|
||||
case 'Apple_Terminal': {
|
||||
return 2;
|
||||
}
|
||||
// No default
|
||||
}
|
||||
}
|
||||
|
||||
if (/-256(color)?$/i.test(env.TERM)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if ('COLORTERM' in env) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
export function createSupportsColor(stream, options = {}) {
|
||||
const level = _supportsColor(stream, {
|
||||
streamIsTTY: stream && stream.isTTY,
|
||||
...options,
|
||||
});
|
||||
|
||||
return translateLevel(level);
|
||||
}
|
||||
|
||||
const supportsColor = {
|
||||
stdout: createSupportsColor({isTTY: tty.isatty(1)}),
|
||||
stderr: createSupportsColor({isTTY: tty.isatty(2)}),
|
||||
};
|
||||
|
||||
export default supportsColor;
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
'use strict';
|
||||
const chalk = require('../source');
|
||||
import chalk, {chalkStderr} from '../source/index.js';
|
||||
|
||||
console.log(`${chalk.hex('#ff6159')('testout')} ${chalk.stderr.hex('#ff6159')('testerr')}`);
|
||||
console.log(`${chalk.hex('#ff6159')('testout')} ${chalkStderr.hex('#ff6159')('testerr')}`);
|
||||
|
|
|
|||
|
|
@ -1,21 +0,0 @@
|
|||
'use strict';
|
||||
const resolveFrom = require('resolve-from');
|
||||
|
||||
const DEFAULT = {
|
||||
stdout: {
|
||||
level: 3,
|
||||
hasBasic: true,
|
||||
has256: true,
|
||||
has16m: true
|
||||
},
|
||||
stderr: {
|
||||
level: 3,
|
||||
hasBasic: true,
|
||||
has256: true,
|
||||
has16m: true
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = (dir, override) => {
|
||||
require.cache[resolveFrom(dir, 'supports-color')] = {exports: override || DEFAULT};
|
||||
};
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import process from 'node:process';
|
||||
import test from 'ava';
|
||||
import chalk, {Chalk, chalkStderr} from '../source/index.js';
|
||||
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname);
|
||||
|
||||
const chalk = require('../source');
|
||||
chalk.level = 3;
|
||||
chalkStderr.level = 3;
|
||||
|
||||
console.log('TERM:', process.env.TERM || '[none]');
|
||||
console.log('platform:', process.platform || '[unknown]');
|
||||
|
|
@ -21,7 +21,7 @@ test('support automatic casting to string', t => {
|
|||
t.is(chalk(123), '123');
|
||||
|
||||
t.is(chalk.bold(['foo', 'bar']), '\u001B[1mfoo,bar\u001B[22m');
|
||||
t.is(chalk.green(98765), '\u001B[32m98765\u001B[39m');
|
||||
t.is(chalk.green(98_765), '\u001B[32m98765\u001B[39m');
|
||||
});
|
||||
|
||||
test('style string', t => {
|
||||
|
|
@ -38,14 +38,14 @@ test('support applying multiple styles at once', t => {
|
|||
test('support nesting styles', t => {
|
||||
t.is(
|
||||
chalk.red('foo' + chalk.underline.bgBlue('bar') + '!'),
|
||||
'\u001B[31mfoo\u001B[4m\u001B[44mbar\u001B[49m\u001B[24m!\u001B[39m'
|
||||
'\u001B[31mfoo\u001B[4m\u001B[44mbar\u001B[49m\u001B[24m!\u001B[39m',
|
||||
);
|
||||
});
|
||||
|
||||
test('support nesting styles of the same type (color, underline, bg)', t => {
|
||||
t.is(
|
||||
chalk.red('a' + chalk.yellow('b' + chalk.green('c') + 'b') + 'c'),
|
||||
'\u001B[31ma\u001B[33mb\u001B[32mc\u001B[39m\u001B[31m\u001B[33mb\u001B[39m\u001B[31mc\u001B[39m'
|
||||
'\u001B[31ma\u001B[33mb\u001B[32mc\u001B[39m\u001B[31m\u001B[33mb\u001B[39m\u001B[31mc\u001B[39m',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -95,26 +95,32 @@ test('line breaks should open and close colors with CRLF', t => {
|
|||
});
|
||||
|
||||
test('properly convert RGB to 16 colors on basic color terminals', t => {
|
||||
t.is(new chalk.Instance({level: 1}).hex('#FF0000')('hello'), '\u001B[91mhello\u001B[39m');
|
||||
t.is(new chalk.Instance({level: 1}).bgHex('#FF0000')('hello'), '\u001B[101mhello\u001B[49m');
|
||||
t.is(new Chalk({level: 1}).hex('#FF0000')('hello'), '\u001B[91mhello\u001B[39m');
|
||||
t.is(new Chalk({level: 1}).bgHex('#FF0000')('hello'), '\u001B[101mhello\u001B[49m');
|
||||
});
|
||||
|
||||
test('properly convert RGB to 256 colors on basic color terminals', t => {
|
||||
t.is(new chalk.Instance({level: 2}).hex('#FF0000')('hello'), '\u001B[38;5;196mhello\u001B[39m');
|
||||
t.is(new chalk.Instance({level: 2}).bgHex('#FF0000')('hello'), '\u001B[48;5;196mhello\u001B[49m');
|
||||
t.is(new chalk.Instance({level: 3}).bgHex('#FF0000')('hello'), '\u001B[48;2;255;0;0mhello\u001B[49m');
|
||||
t.is(new Chalk({level: 2}).hex('#FF0000')('hello'), '\u001B[38;5;196mhello\u001B[39m');
|
||||
t.is(new Chalk({level: 2}).bgHex('#FF0000')('hello'), '\u001B[48;5;196mhello\u001B[49m');
|
||||
t.is(new Chalk({level: 3}).bgHex('#FF0000')('hello'), '\u001B[48;2;255;0;0mhello\u001B[49m');
|
||||
});
|
||||
|
||||
test('don\'t emit RGB codes if level is 0', t => {
|
||||
t.is(new chalk.Instance({level: 0}).hex('#FF0000')('hello'), 'hello');
|
||||
t.is(new chalk.Instance({level: 0}).bgHex('#FF0000')('hello'), 'hello');
|
||||
t.is(new Chalk({level: 0}).hex('#FF0000')('hello'), 'hello');
|
||||
t.is(new Chalk({level: 0}).bgHex('#FF0000')('hello'), 'hello');
|
||||
});
|
||||
|
||||
test('supports blackBright color', t => {
|
||||
t.is(chalk.blackBright('foo'), '\u001B[90mfoo\u001B[39m');
|
||||
});
|
||||
|
||||
test('sets correct level for chalk.stderr and respects it', t => {
|
||||
t.is(chalk.stderr.level, 3);
|
||||
t.is(chalk.stderr.red.bold('foo'), '\u001B[31m\u001B[1mfoo\u001B[22m\u001B[39m');
|
||||
test('sets correct level for chalkStderr and respects it', t => {
|
||||
t.is(chalkStderr.level, 3);
|
||||
t.is(chalkStderr.red.bold('foo'), '\u001B[31m\u001B[1mfoo\u001B[22m\u001B[39m');
|
||||
});
|
||||
|
||||
test('keeps function prototype methods', t => {
|
||||
t.is(chalk.apply(chalk, ['foo']), 'foo');
|
||||
t.is(chalk.bind(chalk, 'foo')(), 'foo');
|
||||
t.is(chalk.call(chalk, 'foo'), 'foo');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
import test from 'ava';
|
||||
|
||||
const chalk = require('../source');
|
||||
|
||||
test('Chalk.constructor should throw an expected error', t => {
|
||||
const expectedError = t.throws(() => {
|
||||
chalk.constructor();
|
||||
});
|
||||
|
||||
t.is(expectedError.message, '`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
|
||||
|
||||
t.throws(() => {
|
||||
new chalk.constructor(); // eslint-disable-line no-new
|
||||
});
|
||||
});
|
||||
|
|
@ -1,12 +1,10 @@
|
|||
import test from 'ava';
|
||||
import chalk, {Chalk} from '../source/index.js';
|
||||
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname);
|
||||
|
||||
const chalk = require('../source');
|
||||
chalk.level = 1;
|
||||
|
||||
test('create an isolated context where colors can be disabled (by level)', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
const instance = new Chalk({level: 0});
|
||||
t.is(instance.red('foo'), 'foo');
|
||||
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
instance.level = 2;
|
||||
|
|
@ -16,11 +14,11 @@ test('create an isolated context where colors can be disabled (by level)', t =>
|
|||
test('the `level` option should be a number from 0 to 3', t => {
|
||||
/* eslint-disable no-new */
|
||||
t.throws(() => {
|
||||
new chalk.Instance({level: 10});
|
||||
}, /should be an integer from 0 to 3/);
|
||||
new Chalk({level: 10});
|
||||
}, {message: /should be an integer from 0 to 3/});
|
||||
|
||||
t.throws(() => {
|
||||
new chalk.Instance({level: -1});
|
||||
}, /should be an integer from 0 to 3/);
|
||||
new Chalk({level: -1});
|
||||
}, {message: /should be an integer from 0 to 3/});
|
||||
/* eslint-enable no-new */
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
import path from 'path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import test from 'ava';
|
||||
import execa from 'execa';
|
||||
import {execaNode} from 'execa';
|
||||
import chalk from '../source/index.js';
|
||||
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname);
|
||||
|
||||
const chalk = require('../source');
|
||||
chalk.level = 1;
|
||||
|
||||
test('don\'t output colors when manually disabled', t => {
|
||||
const oldLevel = chalk.level;
|
||||
|
|
@ -40,6 +38,6 @@ test('propagate enable/disable changes from child colors', t => {
|
|||
});
|
||||
|
||||
test('disable colors if they are not supported', async t => {
|
||||
const {stdout} = await execa.node(path.join(__dirname, '_fixture'));
|
||||
const {stdout} = await execaNode(fileURLToPath(new URL('_fixture.js', import.meta.url)));
|
||||
t.is(stdout, 'testout testerr');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,22 +1,22 @@
|
|||
import test from 'ava';
|
||||
import chalk from '../source/index.js';
|
||||
|
||||
// TODO: Do this when ESM supports loader hooks
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname, {
|
||||
stdout: {
|
||||
level: 0,
|
||||
hasBasic: false,
|
||||
has256: false,
|
||||
has16m: false
|
||||
},
|
||||
stderr: {
|
||||
level: 0,
|
||||
hasBasic: false,
|
||||
has256: false,
|
||||
has16m: false
|
||||
}
|
||||
});
|
||||
|
||||
const chalk = require('../source');
|
||||
// require('./_supports-color')(__dirname, {
|
||||
// stdout: {
|
||||
// level: 0,
|
||||
// hasBasic: false,
|
||||
// has256: false,
|
||||
// has16m: false
|
||||
// },
|
||||
// stderr: {
|
||||
// level: 0,
|
||||
// hasBasic: false,
|
||||
// has256: false,
|
||||
// has16m: false
|
||||
// }
|
||||
// });
|
||||
|
||||
test('colors can be forced by using chalk.level', t => {
|
||||
chalk.level = 1;
|
||||
|
|
|
|||
|
|
@ -1,196 +0,0 @@
|
|||
/* eslint-disable unicorn/no-hex-escape */
|
||||
import test from 'ava';
|
||||
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname);
|
||||
|
||||
const chalk = require('../source');
|
||||
|
||||
test('return an empty string for an empty literal', t => {
|
||||
const instance = new chalk.Instance();
|
||||
t.is(instance``, '');
|
||||
});
|
||||
|
||||
test('return a regular string for a literal with no templates', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`hello`, 'hello');
|
||||
});
|
||||
|
||||
test('correctly perform template parsing', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`{bold Hello, {cyan World!} This is a} test. {green Woo!}`,
|
||||
instance.bold('Hello,', instance.cyan('World!'), 'This is a') + ' test. ' + instance.green('Woo!'));
|
||||
});
|
||||
|
||||
test('correctly perform template substitutions', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
const name = 'Sindre';
|
||||
const exclamation = 'Neat';
|
||||
t.is(instance`{bold Hello, {cyan.inverse ${name}!} This is a} test. {green ${exclamation}!}`,
|
||||
instance.bold('Hello,', instance.cyan.inverse(name + '!'), 'This is a') + ' test. ' + instance.green(exclamation + '!'));
|
||||
});
|
||||
|
||||
test('correctly perform nested template substitutions', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
const name = 'Sindre';
|
||||
const exclamation = 'Neat';
|
||||
t.is(instance.bold`Hello, {cyan.inverse ${name}!} This is a` + ' test. ' + instance.green`${exclamation}!`,
|
||||
instance.bold('Hello,', instance.cyan.inverse(name + '!'), 'This is a') + ' test. ' + instance.green(exclamation + '!'));
|
||||
|
||||
t.is(instance.red.bgGreen.bold`Hello {italic.blue ${name}}`,
|
||||
instance.red.bgGreen.bold('Hello ' + instance.italic.blue(name)));
|
||||
|
||||
t.is(instance.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`,
|
||||
instance.strikethrough.cyanBright.bgBlack('Works with ' + instance.reset.bold('numbers') + ' ' + instance.bold.red(1)));
|
||||
|
||||
t.is(chalk.bold`Also works on the shared {bgBlue chalk} object`,
|
||||
'\u001B[1mAlso works on the shared \u001B[1m' +
|
||||
'\u001B[44mchalk\u001B[49m\u001B[22m' +
|
||||
'\u001B[1m object\u001B[22m');
|
||||
});
|
||||
|
||||
test('correctly parse and evaluate color-convert functions', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
t.is(instance`{bold.rgb(144,10,178).inverse Hello, {~inverse there!}}`,
|
||||
'\u001B[1m\u001B[38;2;144;10;178m\u001B[7mHello, ' +
|
||||
'\u001B[27m\u001B[39m\u001B[22m\u001B[1m' +
|
||||
'\u001B[38;2;144;10;178mthere!\u001B[39m\u001B[22m');
|
||||
|
||||
t.is(instance`{bold.bgRgb(144,10,178).inverse Hello, {~inverse there!}}`,
|
||||
'\u001B[1m\u001B[48;2;144;10;178m\u001B[7mHello, ' +
|
||||
'\u001B[27m\u001B[49m\u001B[22m\u001B[1m' +
|
||||
'\u001B[48;2;144;10;178mthere!\u001B[49m\u001B[22m');
|
||||
});
|
||||
|
||||
test('properly handle escapes', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
t.is(instance`{bold hello \{in brackets\}}`,
|
||||
'\u001B[1mhello {in brackets}\u001B[22m');
|
||||
});
|
||||
|
||||
test('throw if there is an unclosed block', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
try {
|
||||
console.log(instance`{bold this shouldn't appear ever\}`);
|
||||
t.fail();
|
||||
} catch (error) {
|
||||
t.is(error.message, 'Chalk template literal is missing 1 closing bracket (`}`)');
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(instance`{bold this shouldn't {inverse appear {underline ever\} :) \}`);
|
||||
t.fail();
|
||||
} catch (error) {
|
||||
t.is(error.message, 'Chalk template literal is missing 3 closing brackets (`}`)');
|
||||
}
|
||||
});
|
||||
|
||||
test('throw if there is an invalid style', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
try {
|
||||
console.log(instance`{abadstylethatdoesntexist this shouldn't appear ever}`);
|
||||
t.fail();
|
||||
} catch (error) {
|
||||
t.is(error.message, 'Unknown Chalk style: abadstylethatdoesntexist');
|
||||
}
|
||||
});
|
||||
|
||||
test('properly style multiline color blocks', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
t.is(
|
||||
instance`{bold
|
||||
Hello! This is a
|
||||
${'multiline'} block!
|
||||
:)
|
||||
} {underline
|
||||
I hope you enjoy
|
||||
}`,
|
||||
'\u001B[1m\u001B[22m\n' +
|
||||
'\u001B[1m\t\t\tHello! This is a\u001B[22m\n' +
|
||||
'\u001B[1m\t\t\tmultiline block!\u001B[22m\n' +
|
||||
'\u001B[1m\t\t\t:)\u001B[22m\n' +
|
||||
'\u001B[1m\t\t\u001B[22m \u001B[4m\u001B[24m\n' +
|
||||
'\u001B[4m\t\t\tI hope you enjoy\u001B[24m\n' +
|
||||
'\u001B[4m\t\t\u001B[24m'
|
||||
);
|
||||
});
|
||||
|
||||
test('escape interpolated values', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`Hello {bold hi}`, 'Hello hi');
|
||||
t.is(instance`Hello ${'{bold hi}'}`, 'Hello {bold hi}');
|
||||
});
|
||||
|
||||
test('allow custom colors (themes) on custom contexts', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
instance.rose = instance.hex('#F6D9D9');
|
||||
t.is(instance`Hello, {rose Rose}.`, 'Hello, \u001B[38;2;246;217;217mRose\u001B[39m.');
|
||||
});
|
||||
|
||||
test('correctly parse newline literals (bug #184)', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`Hello
|
||||
{red there}`, 'Hello\nthere');
|
||||
});
|
||||
|
||||
test('correctly parse newline escapes (bug #177)', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`Hello\nthere!`, 'Hello\nthere!');
|
||||
});
|
||||
|
||||
test('correctly parse escape in parameters (bug #177 comment 318622809)', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
const string = '\\';
|
||||
t.is(instance`{blue ${string}}`, '\\');
|
||||
});
|
||||
|
||||
test('correctly parses unicode/hex escapes', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`\u0078ylophones are fo\x78y! {magenta.inverse \u0078ylophones are fo\x78y!}`,
|
||||
'xylophones are foxy! xylophones are foxy!');
|
||||
});
|
||||
|
||||
test('correctly parses string arguments', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
t.is(instance`{keyword('black').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
|
||||
t.is(instance`{keyword('blac\x6B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
|
||||
t.is(instance`{keyword('blac\u006B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
|
||||
});
|
||||
|
||||
test('throws if a bad argument is encountered', t => {
|
||||
const instance = new chalk.Instance({level: 3}); // Keep level at least 1 in case we optimize for disabled chalk instances
|
||||
try {
|
||||
console.log(instance`{keyword(????) hi}`);
|
||||
t.fail();
|
||||
} catch (error) {
|
||||
t.is(error.message, 'Invalid Chalk template style argument: ???? (in style \'keyword\')');
|
||||
}
|
||||
});
|
||||
|
||||
test('throws if an extra unescaped } is found', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
try {
|
||||
console.log(instance`{red hi!}}`);
|
||||
t.fail();
|
||||
} catch (error) {
|
||||
t.is(error.message, 'Found extraneous } in Chalk template literal');
|
||||
}
|
||||
});
|
||||
|
||||
test('should not parse upper-case escapes', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`\N\n\T\t\X07\x07\U000A\u000A\U000a\u000a`, 'N\nT\tX07\x07U000A\u000AU000a\u000A');
|
||||
});
|
||||
|
||||
test('should properly handle undefined template interpolated values', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
t.is(instance`hello ${undefined}`, 'hello undefined');
|
||||
t.is(instance`hello ${null}`, 'hello null');
|
||||
});
|
||||
|
||||
test('should allow bracketed Unicode escapes', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
t.is(instance`\u{AB}`, '\u{AB}');
|
||||
t.is(instance`This is a {bold \u{AB681}} test`, 'This is a \u001B[1m\u{AB681}\u001B[22m test');
|
||||
t.is(instance`This is a {bold \u{10FFFF}} test`, 'This is a \u001B[1m\u{10FFFF}\u001B[22m test');
|
||||
});
|
||||
|
|
@ -1,24 +1,22 @@
|
|||
import test from 'ava';
|
||||
import chalk, {Chalk} from '../source/index.js';
|
||||
|
||||
// Spoof supports-color
|
||||
require('./_supports-color')(__dirname);
|
||||
|
||||
const chalk = require('../source');
|
||||
chalk.level = 1;
|
||||
|
||||
test('visible: normal output when level > 0', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
const instance = new Chalk({level: 3});
|
||||
t.is(instance.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
t.is(instance.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
});
|
||||
|
||||
test('visible: no output when level is too low', t => {
|
||||
const instance = new chalk.Instance({level: 0});
|
||||
const instance = new Chalk({level: 0});
|
||||
t.is(instance.visible.red('foo'), '');
|
||||
t.is(instance.red.visible('foo'), '');
|
||||
});
|
||||
|
||||
test('test switching back and forth between level == 0 and level > 0', t => {
|
||||
const instance = new chalk.Instance({level: 3});
|
||||
const instance = new Chalk({level: 3});
|
||||
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
t.is(instance.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
t.is(instance.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue