Compare commits

..

41 commits
v5.0.0 ... main

Author SHA1 Message Date
Mohamed Hamed
aa06bb5ac3
Fix typos (#664) 2026-01-27 13:30:36 +07:00
Sindre Sorhus
51557784b8 5.6.2 2025-09-08 21:47:34 +07:00
Sindre Sorhus
5c91505e18 5.6.0 2025-08-17 14:26:22 +07:00
Sindre Sorhus
a8f5bf7a67 Make WezTerm terminal use true color 2025-08-17 14:25:29 +07:00
Sindre Sorhus
67db246ae0 5.5.0 2025-08-04 01:17:43 +02:00
Brice
79ee2d386c
Make Ghostty terminal use true color (#653) 2025-08-04 01:14:54 +02:00
Sindre Sorhus
5dbc1e2633 5.4.1 2024-12-21 18:04:25 +01:00
Edwin Kofler
4ebb62d1ca
Fix navigator not defined ReferenceError (#642) 2024-12-21 18:01:49 +01:00
Sindre Sorhus
fc809b686d Readme tweak 2024-12-18 19:10:23 +01:00
Sindre Sorhus
83acfcf8cb 5.4.0 2024-12-18 18:59:38 +01:00
Sindre Sorhus
f8381204fb Update CIRCLECI environments to return level 3 color support
89a52f4a8e
2024-12-18 18:58:03 +01:00
Sindre Sorhus
4a10354857 Add FAQ to readme 2024-08-13 17:43:03 +02:00
Sindre Sorhus
77126fba13 Meta tweaks 2024-08-08 00:00:20 +02:00
Lightner
795273f17a
Update dependents number in readme (#629) 2024-07-05 12:41:35 +02:00
Richie Bendall
386909ee0b
Tweak example (#623) 2024-01-19 21:36:11 +07:00
Edwin Kofler
2db3c7701e
Remove .replit file (#622) 2024-01-06 02:08:07 +01:00
Sindre Sorhus
f7b29ae8ef Remove repl.it badge
Fixes #587
2023-08-16 12:14:40 +02:00
Sindre Sorhus
f399cd0ff6 Meta tweaks 2023-06-29 14:45:41 +02:00
Sindre Sorhus
72c742d471 5.3.0 2023-06-29 12:56:55 +02:00
Sindre Sorhus
5aafc0af74 Add sideEffects field to package.json
Fixes #585
2023-06-29 12:52:59 +02:00
Sindre Sorhus
df0e69df51 Fix CI 2023-06-29 12:50:22 +02:00
silverwind
29b856959f
Update supports-color to 9.4.0 (#603)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2023-06-29 12:47:28 +02:00
Sindre Sorhus
a370f468a4 5.2.0 2022-12-08 19:46:06 +01:00
idanran
7443e9faa0
Update supports-color dependency (#579) 2022-12-08 19:43:43 +01:00
Sindre Sorhus
a027e3c1e0 Minor tweaks 2022-11-28 14:15:46 +07:00
LitoMore
79c56dfc1e
Update Replit badge (#576) 2022-10-30 23:54:53 +07:00
Daniel Li
c3d14f9ea8
Update link to Truecolor in the readme (#573) 2022-10-20 17:29:51 +07:00
Sindre Sorhus
158bf4429e 5.1.2 2022-10-12 23:31:43 +07:00
LitoMore
a34bcf6327
Fix exported styles names (#569) 2022-10-12 23:30:36 +07:00
Sindre Sorhus
1b4cd21fb1 5.1.1 2022-10-12 16:36:43 +07:00
LitoMore
6e0df055f4
Export styles from ansi-styles (#567) 2022-10-12 16:35:02 +07:00
Sindre Sorhus
92c55db46f 5.1.0 2022-10-05 21:45:55 +07:00
LitoMore
d7d75717b3
Expose style names (#566)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2022-10-05 21:44:40 +07:00
Sindre Sorhus
96f44c976b Meta tweaks 2022-10-05 21:43:01 +07:00
Matt Schlenker
c2311622c3
Use template literal types for simple color name transformations in the TypeScript types (#564) 2022-09-25 12:24:19 +07:00
Sindre Sorhus
ba5c385ecf Update screenshot
Fixes #554
2022-07-03 00:36:34 +02:00
LitoMore
503b9d35cd
Update Replit badge (#551) 2022-06-26 14:58:46 +02:00
Richie Bendall
b17d862944
Improve browser detection (#542) 2022-03-30 12:41:57 +07:00
CommanderRoot
d28690e66b
Refactor: Replace deprecated String#substr() (#541) 2022-03-28 01:11:02 +07:00
Sindre Sorhus
bccde97f8a 5.0.1 2022-03-09 01:43:33 +07:00
Sindre Sorhus
85f7e96f75 Add main field to package.json for backwards compatibiltiy
Fixes #536
2022-03-09 01:42:04 +07:00
17 changed files with 373 additions and 241 deletions

View file

@ -10,12 +10,12 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
node-version: node-version:
- 18
- 16 - 16
- 14 - 14
- 12
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- uses: actions/setup-node@v2 - uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- run: npm install - run: npm install

View file

@ -1,2 +0,0 @@
language = "nodejs"
run = "cd examples && node rainbow"

View file

@ -1,6 +1,6 @@
import {setTimeout as delay} from 'node:timers/promises';
import convertColor from 'color-convert'; import convertColor from 'color-convert';
import updateLog from 'log-update'; import updateLog from 'log-update';
import delay from 'yoctodelay';
import chalk from '../source/index.js'; import chalk from '../source/index.js';
const ignoreChars = /[^!-~]/g; const ignoreChars = /[^!-~]/g;
@ -10,7 +10,7 @@ function rainbow(string, offset) {
return string; return string;
} }
const hueStep = 360 / string.replace(ignoreChars, '').length; const hueStep = 360 / string.replaceAll(ignoreChars, '').length;
let hue = offset % 360; let hue = offset % 360;
const characters = []; const characters = [];
@ -33,8 +33,6 @@ async function animateString(string) {
} }
} }
(async () => {
console.log(); console.log();
await animateString('We hope you enjoy Chalk! <3'); await animateString('We hope you enjoy Chalk! <3');
console.log(); console.log();
})();

View file

@ -6,7 +6,16 @@ import chalk from '../source/index.js';
for (const key of Object.keys(styles)) { for (const key of Object.keys(styles)) {
let returnValue = key; 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; continue;
} }

BIN
media/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

View file

@ -1,11 +1,12 @@
{ {
"name": "chalk", "name": "chalk",
"version": "5.0.0", "version": "5.6.2",
"description": "Terminal string styling done right", "description": "Terminal string styling done right",
"license": "MIT", "license": "MIT",
"repository": "chalk/chalk", "repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1", "funding": "https://github.com/chalk/chalk?sponsor=1",
"type": "module", "type": "module",
"main": "./source/index.js",
"exports": "./source/index.js", "exports": "./source/index.js",
"imports": { "imports": {
"#ansi-styles": "./source/vendor/ansi-styles/index.js", "#ansi-styles": "./source/vendor/ansi-styles/index.js",
@ -15,6 +16,7 @@
} }
}, },
"types": "./source/index.d.ts", "types": "./source/index.d.ts",
"sideEffects": false,
"engines": { "engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0" "node": "^12.17.0 || ^14.13 || >=16.0.0"
}, },
@ -57,12 +59,16 @@
"log-update": "^5.0.0", "log-update": "^5.0.0",
"matcha": "^0.7.0", "matcha": "^0.7.0",
"tsd": "^0.19.0", "tsd": "^0.19.0",
"xo": "^0.47.0", "xo": "^0.57.0",
"yoctodelay": "^2.0.0" "yoctodelay": "^2.0.0"
}, },
"xo": { "xo": {
"rules": { "rules": {
"unicorn/prefer-string-slice": "off" "unicorn/prefer-string-slice": "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": { "c8": {

102
readme.md
View file

@ -10,63 +10,15 @@
> Terminal string styling done right > Terminal string styling done right
[![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk) [![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk)
[![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents)
[![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk)
[![Support Chalk on DEV](https://badge.devprotocol.xyz/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15/descriptive)](https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900"> ![](media/screenshot.png)
<br> ## Info
--- - [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
<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="230"/>
</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>
<br>
<a href="https://strapi.io/?ref=sindresorhus">
<div>
<img src="https://sindresorhus.com/assets/thanks/strapi-logo-white-bg.png" width="220" alt="Strapi">
</div>
<b>Strapi is the leading open-source headless CMS.</b>
<div>
<sup>Its 100% JavaScript, fully customizable, and developer-first.</sup>
</div>
</a>
</p>
</div>
---
<br>
## Highlights ## Highlights
@ -79,7 +31,7 @@
- Doesn't extend `String.prototype` - Doesn't extend `String.prototype`
- Clean and focused - Clean and focused
- Actively maintained - Actively maintained
- [Used by ~76,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 26, 2021 - [Used by ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024
## Install ## Install
@ -200,6 +152,22 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
`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. `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 ## Styles
### Modifiers ### Modifiers
@ -255,7 +223,7 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
## 256 and Truecolor color support ## 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). 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).
@ -283,15 +251,25 @@ Since Chrome 69, ANSI escape codes are natively supported in the developer conso
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`. 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 wont 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 wont 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 ## Related
@ -311,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 - [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 - [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
*(Not accepting additional entries)*
## Maintainers ## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus) - [Sindre Sorhus](https://github.com/sindresorhus)

145
source/index.d.ts vendored
View file

@ -1,76 +1,14 @@
// TODO: Make it this when TS suports that. // TODO: Make it this when TS suports that.
// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles';
// import {ColorInfo, ColorSupportLevel} from '#supports-color'; // 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'; import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js';
/**
Basic foreground colors.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export 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/main/readme.md#256-and-truecolor-color-support)
*/
export 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/main/readme.md#256-and-truecolor-color-support)
*/
export type Color = ForegroundColor | BackgroundColor;
export type Modifiers =
| 'reset'
| 'bold'
| 'dim'
| 'italic'
| 'underline'
| 'overline'
| 'inverse'
| 'hidden'
| 'strikethrough'
| 'visible';
export interface Options { export interface Options {
/** /**
Specify the color support for Chalk. Specify the color support for Chalk.
@ -308,6 +246,12 @@ export const supportsColor: ColorInfo;
export const chalkStderr: typeof chalk; export const chalkStderr: typeof chalk;
export const supportsColorStderr: typeof supportsColor; export const supportsColorStderr: typeof supportsColor;
export {
ModifierName, ForegroundColorName, BackgroundColorName, ColorName,
modifierNames, foregroundColorNames, backgroundColorNames, colorNames,
// } from '#ansi-styles';
} from './vendor/ansi-styles/index.js';
export { export {
ColorInfo, ColorInfo,
ColorSupport, ColorSupport,
@ -315,4 +259,67 @@ export {
// } from '#supports-color'; // } from '#supports-color';
} from './vendor/supports-color/index.js'; } 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; export default chalk;

View file

@ -204,6 +204,19 @@ Object.defineProperties(createChalk.prototype, styles);
const chalk = createChalk(); const chalk = createChalk();
export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});
export {
modifierNames,
foregroundColorNames,
backgroundColorNames,
colorNames,
// 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';
export { export {
stdoutColor as supportsColor, stdoutColor as supportsColor,
stderrColor as supportsColorStderr, stderrColor as supportsColorStderr,

View file

@ -1,5 +1,24 @@
import {expectType, expectAssignable, expectError} from 'tsd'; import {
import chalk, {Chalk, ChalkInstance, Color, ColorInfo, ColorSupport, ColorSupportLevel, chalkStderr, supportsColor, supportsColorStderr} from './index.js'; 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 - // - supportsColor -
expectType<ColorInfo>(supportsColor); expectType<ColorInfo>(supportsColor);
@ -141,6 +160,20 @@ expectType<string>(chalk.underline``);
expectType<string>(chalk.red.bgGreen.bold`Hello {italic.blue ${name}}`); expectType<string>(chalk.red.bgGreen.bold`Hello {italic.blue ${name}}`);
expectType<string>(chalk.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`); expectType<string>(chalk.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`);
// -- Color types == // -- Modifiers types
expectAssignable<Color>('red'); expectAssignable<ModifierName>('strikethrough');
expectError<Color>('hotpink'); 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');

View file

@ -9,7 +9,7 @@ export function stringReplaceAll(string, substring, replacer) {
let endIndex = 0; let endIndex = 0;
let returnValue = ''; let returnValue = '';
do { do {
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; returnValue += string.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength; endIndex = index + substringLength;
index = string.indexOf(substring, endIndex); index = string.indexOf(substring, endIndex);
} while (index !== -1); } while (index !== -1);
@ -23,7 +23,7 @@ export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let returnValue = ''; let returnValue = '';
do { do {
const gotCR = string[index - 1] === '\r'; const gotCR = string[index - 1] === '\r';
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1; endIndex = index + 1;
index = string.indexOf('\n', endIndex); index = string.indexOf('\n', endIndex);
} while (index !== -1); } while (index !== -1);

View file

@ -180,6 +180,52 @@ export interface ConvertColor {
hexToAnsi(hex: string): number; 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: { declare const ansiStyles: {
readonly modifier: Modifier; readonly modifier: Modifier;
readonly color: ColorBase & ForegroundColor; readonly color: ColorBase & ForegroundColor;

View file

@ -6,8 +6,6 @@ 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 wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
function assembleStyles() {
const codes = new Map();
const styles = { const styles = {
modifier: { modifier: {
reset: [0, 0], reset: [0, 0],
@ -33,6 +31,8 @@ function assembleStyles() {
// Bright color // Bright color
blackBright: [90, 39], blackBright: [90, 39],
gray: [90, 39], // Alias of `blackBright`
grey: [90, 39], // Alias of `blackBright`
redBright: [91, 39], redBright: [91, 39],
greenBright: [92, 39], greenBright: [92, 39],
yellowBright: [93, 39], yellowBright: [93, 39],
@ -53,6 +53,8 @@ function assembleStyles() {
// Bright color // Bright color
bgBlackBright: [100, 49], bgBlackBright: [100, 49],
bgGray: [100, 49], // Alias of `bgBlackBright`
bgGrey: [100, 49], // Alias of `bgBlackBright`
bgRedBright: [101, 49], bgRedBright: [101, 49],
bgGreenBright: [102, 49], bgGreenBright: [102, 49],
bgYellowBright: [103, 49], bgYellowBright: [103, 49],
@ -63,11 +65,13 @@ function assembleStyles() {
}, },
}; };
// Alias bright black as gray (and grey) export const modifierNames = Object.keys(styles.modifier);
styles.color.gray = styles.color.blackBright; export const foregroundColorNames = Object.keys(styles.color);
styles.bgColor.bgGray = styles.bgColor.bgBlackBright; export const backgroundColorNames = Object.keys(styles.bgColor);
styles.color.grey = styles.color.blackBright; export const colorNames = [...foregroundColorNames, ...backgroundColorNames];
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
function assembleStyles() {
const codes = new Map();
for (const [groupName, group] of Object.entries(styles)) { for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) { for (const [styleName, style] of Object.entries(group)) {
@ -105,7 +109,7 @@ function assembleStyles() {
// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
Object.defineProperties(styles, { Object.defineProperties(styles, {
rgbToAnsi256: { rgbToAnsi256: {
value: (red, green, blue) => { value(red, green, blue) {
// We use the extended greyscale palette here, with the exception of // We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades. // black and white. normal palette only has 4 greyscale shades.
if (red === green && green === blue) { if (red === green && green === blue) {
@ -128,13 +132,13 @@ function assembleStyles() {
enumerable: false, enumerable: false,
}, },
hexToRgb: { hexToRgb: {
value: hex => { value(hex) {
const matches = /(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) { if (!matches) {
return [0, 0, 0]; return [0, 0, 0];
} }
let {colorString} = matches.groups; let [colorString] = matches;
if (colorString.length === 3) { if (colorString.length === 3) {
colorString = [...colorString].map(character => character + character).join(''); colorString = [...colorString].map(character => character + character).join('');
@ -157,7 +161,7 @@ function assembleStyles() {
enumerable: false, enumerable: false,
}, },
ansi256ToAnsi: { ansi256ToAnsi: {
value: code => { value(code) {
if (code < 8) { if (code < 8) {
return 30 + code; return 30 + code;
} }

View file

@ -1,13 +1,30 @@
/* eslint-env browser */ /* eslint-env browser */
const isBlinkBasedBrowser = /\b(Chrome|Chromium)\//.test(navigator.userAgent); const level = (() => {
if (!('navigator' in globalThis)) {
return 0;
}
const colorSupport = isBlinkBasedBrowser ? { if (globalThis.navigator.userAgentData) {
level: 1, 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, hasBasic: true,
has256: false, has256: level >= 2,
has16m: false, has16m: level >= 3,
} : false; };
const supportsColor = { const supportsColor = {
stdout: colorSupport, stdout: colorSupport,

View file

@ -1,13 +1,13 @@
import {WriteStream} from 'node:tty'; import type {WriteStream} from 'node:tty';
export interface Options { export type Options = {
/** /**
Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. Whether `process.argv` should be sniffed for `--color` and `--no-color` flags.
@default true @default true
*/ */
readonly sniffFlags?: boolean; readonly sniffFlags?: boolean;
} };
/** /**
Levels: Levels:
@ -21,7 +21,7 @@ export type ColorSupportLevel = 0 | 1 | 2 | 3;
/** /**
Detect whether the terminal supports color. Detect whether the terminal supports color.
*/ */
export interface ColorSupport { export type ColorSupport = {
/** /**
The color level. The color level.
*/ */
@ -41,11 +41,11 @@ export interface ColorSupport {
Whether Truecolor 16 million colors are supported. Whether Truecolor 16 million colors are supported.
*/ */
has16m: boolean; has16m: boolean;
} };
export type ColorInfo = ColorSupport | false; export type ColorInfo = ColorSupport | false;
export function createSupportsColor(stream: WriteStream, options?: Options): ColorInfo; export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo;
declare const supportsColor: { declare const supportsColor: {
stdout: ColorInfo; stdout: ColorInfo;

View file

@ -3,7 +3,8 @@ import os from 'node:os';
import tty from 'node:tty'; import tty from 'node:tty';
// From: https://github.com/sindresorhus/has-flag/blob/main/index.js // From: https://github.com/sindresorhus/has-flag/blob/main/index.js
function hasFlag(flag, argv = process.argv) { /// 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 prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag); const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--'); const terminatorPosition = argv.indexOf('--');
@ -80,6 +81,12 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
} }
} }
// 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) { if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0; return 0;
} }
@ -105,7 +112,11 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
} }
if ('CI' in env) { if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { 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 1;
} }
@ -116,12 +127,19 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
} }
// Check for Azure DevOps pipelines if (env.COLORTERM === 'truecolor') {
if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 3;
return 1;
} }
if (env.COLORTERM === 'truecolor') { if (env.TERM === 'xterm-kitty') {
return 3;
}
if (env.TERM === 'xterm-ghostty') {
return 3;
}
if (env.TERM === 'wezterm') {
return 3; return 3;
} }
@ -129,10 +147,13 @@ function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) { switch (env.TERM_PROGRAM) {
case 'iTerm.app': case 'iTerm.app': {
return version >= 3 ? 3 : 2; return version >= 3 ? 3 : 2;
case 'Apple_Terminal': }
case 'Apple_Terminal': {
return 2; return 2;
}
// No default // No default
} }
} }

View file

@ -38,6 +38,6 @@ test('propagate enable/disable changes from child colors', t => {
}); });
test('disable colors if they are not supported', async t => { test('disable colors if they are not supported', async t => {
const {stdout} = await execaNode(fileURLToPath(new URL('./_fixture.js', import.meta.url))); const {stdout} = await execaNode(fileURLToPath(new URL('_fixture.js', import.meta.url)));
t.is(stdout, 'testout testerr'); t.is(stdout, 'testout testerr');
}); });