Compare commits

...

251 commits
v1.1.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
Sindre Sorhus
4d5c4795ad 5.0.0 2021-11-26 16:57:26 +07:00
Sindre Sorhus
7a6893551d Fix code coverage 2021-11-26 16:55:15 +07:00
Sindre Sorhus
04fdbd6d8d Bundle dependencies 2021-11-26 16:34:27 +07:00
Sindre Sorhus
d7c4aac07e Upgrade dependencies 2021-11-26 16:00:01 +07:00
Richie Bendall
09fd5c4ba8
Re-export types from supports-color (#526) 2021-11-21 13:51:24 +07:00
Richie Bendall
c987c61486
Remove support for tagged template literals (#524) 2021-11-10 16:12:33 +07:00
LightnerDev
f478655c3c
Update dependents number in readme (#521) 2021-10-27 01:22:37 +07:00
Richie Bendall
3761e455a1
Meta tweak (#520) 2021-10-25 02:07:02 +07:00
Sindre Sorhus
95217429be Minor tweaks 2021-10-02 00:02:38 +07:00
Sindre Sorhus
625a285772 Add types field to package.json
Fixes #500
2021-07-30 17:35:30 +02:00
Sindre Sorhus
48d25d156a Meta tweaks 2021-07-30 13:58:57 +02:00
Sindre Sorhus
b68c8b5102 Meta tweaks 2021-05-05 21:40:56 +07:00
Richie Bendall
f8a3642a81
Minor tweaks (#437)
Co-authored-by: Qix <Qix-@users.noreply.github.com>
2021-04-22 15:03:48 +07:00
Richie Bendall
4cf2e40e07
Add overline style and remove keyword, hsl, hsv, hwb and ansi color spaces (#433) 2021-04-22 10:54:42 +07:00
Richie Bendall
0fba91b037
Keep function prototype methods (#434) 2021-04-20 13:48:30 +07:00
Richie Bendall
d798222a5a
Add named exports (#432) 2021-04-17 19:33:03 +07:00
Sindre Sorhus
fa16f4ec37 Require Node.js 12 and move to ESM 2021-04-16 16:22:53 +07:00
Sindre Sorhus
4dab5e1fb6
Meta tweaks 2021-03-13 00:51:42 +07:00
Sindre Sorhus
9bf298571e Meta tweaks 2021-01-30 16:59:16 +07:00
Sindre Sorhus
2a9abb18f4 Rename master branch to main 2021-01-24 14:27:41 +07:00
Sindre Sorhus
97a0861848 Update badge 2021-01-21 10:19:50 +07:00
Sindre Sorhus
0433fcff2a Update a link 2021-01-20 14:45:02 +07:00
Richie Bendall
d5fb377019
Move to GitHub Actions (#426)
* Move to GitHub Actions

* Update readme.md
2021-01-02 20:38:53 +07:00
Sindre Sorhus
ca330532ec
Add @Qix- to funding.yml 2020-12-16 10:09:08 +07:00
Sindre Sorhus
e304e8c230 Add Dev badge 2020-12-08 21:45:51 +07:00
Richie Bendall
02abeebac3
Only iterate through models once (#421) 2020-11-21 20:07:13 +07:00
Toon Baeyens
72299f99a0
remove fixed number of iterations (#406) 2020-11-20 15:26:28 +01:00
Richie Bendall
c0d8e7ed8a
Update test dependencies (#414) 2020-10-03 23:56:24 +02:00
Richie Bendall
b31d6fb48a
Add browser support information (#415) 2020-10-03 23:55:17 +02:00
Sindre Sorhus
445092f9af
Update readme.md 2020-09-09 17:48:28 +02:00
Sindre Sorhus
4c3df88472 4.1.0 2020-06-09 15:43:27 +08:00
Toon Baeyens
09ddbadcb5
Support template literals for nested calls (#392)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2020-06-09 15:36:34 +08:00
Steven
55816cdd4d
Update readme links to use https (#396) 2020-04-16 05:56:23 +02:00
Sindre Sorhus
31fa942080 4.0.0 2020-04-02 16:17:06 +08:00
Sindre Sorhus
61999a4e77 Require Node.js 10 2020-04-02 16:10:07 +08:00
Sindre Sorhus
f0f4638a92 Change the TypeScript Level type to be a union instead of enum
Fixes #373
Fixes #382
2020-04-02 15:51:17 +08:00
Richie Bendall
7f21f209da
Properly check if level is an integer (#393) 2020-04-02 15:49:20 +08:00
Bradley Farias
63469d30e4
Use Object.setPrototypeOf as __proto__ could potentially be disabled (#387) 2020-04-02 15:47:12 +08:00
Sindre Sorhus
797461ee32 Meta tweaks 2020-01-01 19:40:12 +01:00
Edwin Kofler
0e6fecc7f7 Add link to replit run (#379) 2019-12-12 21:12:22 +01:00
Sindre Sorhus
20002d8bd1 3.0.0 2019-11-09 13:58:44 +07:00
Sindre Sorhus
b3930189a5 Meta tweaks 2019-11-09 13:57:31 +07:00
Mark Pedrotti
18c280da2e Add ansi and bgAnsi to TypeScript declaration (#369) 2019-11-09 11:22:55 +05:00
Sindre Sorhus
628b5954cf Tidelift tasks 2019-10-30 19:38:56 +07:00
Sindre Sorhus
4de1841129 3.0.0-beta.2 2019-10-08 16:21:40 +07:00
Mark Pedrotti
fb8e85ab87 Add ansi256 and bgAnsi256 to TypeScript declarations (#368) 2019-10-08 16:02:34 +07:00
Mark Pedrotti
eef8c8c191 Replace level list with table in readme.md (#367)
* Replace level list with table in readme.md

* Capitalize table headings and center level numbers
2019-10-01 03:13:15 +02:00
Sindre Sorhus
48905d0805 3.0.0-beta.1 2019-09-27 12:07:07 +07:00
Sindre Sorhus
1953816afd Update dependencies 2019-09-27 11:16:49 +07:00
Yanis Benson
61aca7cb76 Improve require speed (#358) 2019-09-27 10:55:19 +07:00
Khải
4e65299e7b Fix const enum for TypeScript (#364) 2019-09-27 10:53:54 +07:00
Yanis Benson
2a53389d72 Add chalk.stderr (#359) 2019-09-22 16:07:33 +07:00
Simen Bekkhus
6b4d20683f Export TypeScript types for colors and modifiers (#357)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2019-08-22 15:28:25 +02:00
Qix
1f77953f1a Remove the .enabled property in favor of .level (#356) 2019-07-13 12:45:31 +07:00
Ahad Birang
87156ce8e2 Fix support for nested styles (#335) 2019-07-13 01:49:56 +07:00
Sindre Sorhus
c25c32a25f Update dependencies 2019-07-12 14:13:58 +07:00
Sindre Sorhus
655653bb0c Meta tweaks 2019-07-12 14:13:02 +07:00
Boris K
af4a078245 Update docs for FORCE_COLOR environment variable (#315) 2019-07-12 14:11:25 +07:00
Yanis Benson
c08417e88c Improve performance greatly (#337) 2019-07-12 13:40:23 +07:00
Qix
983094883c Fix support for bracketed Unicode escapes in template literals (#350) 2019-07-12 13:35:11 +07:00
Marcos Marado
e2dd171597 Remove outdated info in the readme (#351) 2019-06-30 23:11:52 +07:00
Florian Reuschel
d82b2a6638 Add missing false type to chalk.supportsColor (#347) 2019-06-11 00:47:16 +07:00
Sindre Sorhus
4ab4665994 Tidelift tasks 2019-05-31 14:53:04 +07:00
Sindre Sorhus
4990a3578a Add GitHub Sponsors button to the repo 2019-05-23 16:47:28 +07:00
ExE Boss
b3e9b91405 Fix TypeScript types for supportsColor which is top‑level only (#342)
Co-Authored-By: Dimitri Benin <BendingBender@users.noreply.github.com>
2019-05-11 15:04:20 +07:00
Sindre Sorhus
d3be9c65b1 Drop built-in Flow type definition
I don't want to be responsible for maintaining it.

Submit it to https://github.com/flow-typed/flow-typed if you need it.
2019-05-03 15:03:53 +07:00
Dimitri Benin
98628d9f08 Use CommonJS-compatible export in TypeScript definition (#344) 2019-04-28 11:10:44 +07:00
Sindre Sorhus
7b9211be50 Minor refactoring 2019-03-15 00:08:50 +07:00
Sindre Sorhus
cd5de7a2f6
Remove dim style workaround for Windows (#331)
See: https://github.com/chalk/chalk/pull/330/#issuecomment-471977551

The issue seems to have been fixed in newer Windows 10 builds. We're not interested in adding a conditional for older Windows versions as the fix severely complicates the codebase, and it also creates problems for consumers as it makes the output unpredictable.
2019-03-13 00:24:34 +07:00
Sindre Sorhus
2ca015c4c5
Remove the blue color workaround for Windows (#330)
The illegible blue color has been fixed in Windows 10 build 16257: https://blogs.msdn.microsoft.com/commandline/2017/08/02/updating-the-windows-console-colors/

The workaround causes all kinds of problems, so better to remove it than adding conditionals for older Windows versions.

Fixes #329
2019-03-12 20:31:33 +07:00
Sindre Sorhus
3ef170b457 Require Node.js 8 2019-03-12 20:15:36 +07:00
Tom Sherman
de2f4cd606 Deprecate chalk.constructor() in favor of new chalk.Instance() (#322) 2019-03-12 19:53:03 +07:00
Richie Bendall
60959e05cf Update depended packages count 2019-03-01 07:18:47 +01:00
Jonathan Van Buren
7f6e5630b0 Change tagged template literal argument type to accept unknown instead of just string (#316) 2018-12-28 12:13:56 +01:00
Sindre Sorhus
587a5fbcbb Code style tweaks 2018-12-26 03:13:52 +01:00
Chris Harwood
076f0c9eb6 Add extra level/enabled property info in the readme (#308) 2018-12-26 02:29:32 +01:00
Sindre Sorhus
1284415013 Enforce chalk.constructor to be called with new in TypeScript 2018-12-26 02:27:57 +01:00
Sindre Sorhus
cf6615647a Type definition improvements 2018-12-26 02:27:02 +01:00
Sindre Sorhus
4726b1bfda Update dependencies and meta tweaks 2018-12-26 02:18:40 +01:00
George Gkasdrogkas
90c7a92ff1 Add docs comments and tests for TypeScript definitions (#299)
Fixes #293
2018-12-26 02:06:00 +01:00
Sindre Sorhus
f590a65489
Add security section 2018-12-25 14:45:17 +01:00
Timothy Yung
70bb378e8e Strict mode in Flow definition (#309) 2018-11-30 11:34:09 +07:00
Atif Aziz
b827cb0817 Fix ignore chars regex flags in rainbow example (#306)
Use global matches rather than stopping after the first match.
2018-10-27 21:09:54 +07:00
Sindre Sorhus
1542c85f1b Replace RawGit URL
Fixes #305
2018-10-13 12:32:09 +07:00
Sindre Sorhus
8a090d7885 Add Tidelift mention in the readme 2018-09-30 01:41:55 +07:00
Paul Melnikow
b9c95dbfd2 Add type definitions badge (#286) 2018-09-19 02:20:53 +07:00
Chris Harwood
6a14c58e54 Add failing test for #234 (#235) 2018-09-18 15:48:47 +07:00
Sindre Sorhus
2a678789b1 Validate the level option
Fixes #248
2018-09-18 15:33:20 +07:00
Sindre Sorhus
0307f263cb Require Node.js 6 2018-09-18 14:32:14 +07:00
Sindre Sorhus
70f22d87ba Tiny travis.yml tweak 2018-09-01 02:50:53 +07:00
Sindre Sorhus
a2b5fa22dc
Add some badges to the readme 2018-08-06 15:53:00 +07:00
Sindre Sorhus
a6ad945452 Fix XO linting and update some dev dependencies
Fixes #275
2018-05-28 09:16:44 +07:00
Sindre Sorhus
48ba5b0b9b 2.4.1 2018-04-26 12:15:49 +07:00
Jamie
01cfb5c888 Improve Flow type definition for CommonJS interop (#268) 2018-04-26 12:14:22 +07:00
Sindre Sorhus
fc9a7e369b GitHub now natively supports SVG 2018-04-20 13:42:59 +07:00
Sindre Sorhus
af8b3657e9 2.4.0 2018-04-17 11:28:35 +07:00
Saad Quadri
7c6f83f719 Add Flow type definitions (#260) 2018-04-17 11:26:17 +07:00
Sindre Sorhus
58483b5ab1 Add a related package to the readme 2018-04-05 00:43:46 +07:00
Sindre Sorhus
0dae4c28e1
Add Patreon badge 2018-04-02 14:35:53 +07:00
Sindre Sorhus
84f27d4bd8 2.3.2 2018-03-03 00:43:48 +07:00
Sindre Sorhus
245dfa5c6f Bump dependencies
Closes #255
Fixes #254
Fixes #224
2018-03-03 00:42:56 +07:00
Josh Junon
e80f02e2dd Disable unicorn/no-hex-escape for template tests 2018-02-14 18:30:52 -08:00
Josh Junon
925397a0f5 Disable unicorn/no-unsafe-regex for template parser 2018-02-14 18:30:50 -08:00
Josh Junon
52823001a5 Revert "Fix linting"
This reverts commit 12d1276b36.
2018-02-14 18:28:22 -08:00
Sindre Sorhus
12d1276b36 Fix linting 2018-02-15 00:41:45 +07:00
Sindre Sorhus
576d8d2171 Update URL to XO 2018-02-15 00:15:28 +07:00
Sindre Sorhus
ae8a03f2c5 2.3.1 2018-02-11 20:18:25 +07:00
Sindre Sorhus
b55dd79f8b Force bump dependencies
npm is buggy, so doing this just to be sure.
2018-02-11 20:04:55 +07:00
Kayla Washburn
678152cf19 Update chalk to use the latest updates to supports-color (#247) 2018-02-11 16:59:24 +07:00
Aman Pratap Singh
011dd0421e Fix usage example in the readme (#251) 2018-02-11 16:03:50 +07:00
Mario Nebl
6554030550 Use svg screenshot 2018-01-29 07:20:23 -08:00
Samarth Verma
bc3dd75329 Update usage stats in the readme (#242) 2017-12-31 16:20:49 +01:00
Brandon Smith
a8c60e37fa Fix spelling error in readme (#232) 2017-12-09 11:20:28 +01:00
Andrew
5392313414 Correct HSV and HWB examples 2017-10-25 23:33:12 -07:00
Sindre Sorhus
14e0aa9772 2.3.0 2017-10-24 11:12:53 +07:00
calebboyd
7be154c074 TypeScript fixes (#217) 2017-10-24 11:02:36 +07:00
Josh Junon
e1177ec362 2.2.2 2017-10-23 20:15:51 -07:00
Josh Junon
e2a4aa4275 fix .visible when called after .enable is set to false 2017-10-23 20:12:34 -07:00
Josh Junon
ede310303b add failing test for .visible bug 2017-10-23 20:12:16 -07:00
Josh Junon
6adf5794a3 2.2.1 2017-10-23 19:46:10 -07:00
Danny Kirchmeier
dc092b4a5f Add .visible for emitting text only when enabled (fixes #192) 2017-10-23 19:44:46 -07:00
Sindre Sorhus
4372d27f7e Add Awesome mentioned badge 2017-10-22 15:20:23 +07:00
Sindre Sorhus
d86db88e77 2.2.0 2017-10-18 10:15:39 +07:00
Sindre Sorhus
f0533f655d Bump dev dependencies 2017-10-18 10:14:40 +07:00
calebboyd
f653b061d6 Add TypeScript definitions (#207) 2017-10-18 10:10:43 +07:00
Kevin Martensson
5e6d5fda44 Add strip-ansi-stream to related modules 2017-09-20 18:03:52 +02:00
LitoMore
7898eda561 Update chalk-pipe description 2017-08-24 01:15:18 -07:00
LitoMore
37db75e1fd Add related package in the readme 2017-08-24 01:15:18 -07:00
Sindre Sorhus
a9f0c77142 Use a Map and some minor regex tweaks 2017-08-07 17:42:39 +02:00
Josh Junon
38f641a222 v2.1.0 2017-08-06 20:51:22 -07:00
Josh Junon
69ac663f29 Fix undefined and null interpolated expressions (fixes #194) 2017-08-06 18:58:17 -07:00
Josh Junon
106f086aaf Rewrite templating system (closes #186, fixes #184) 2017-08-06 18:58:17 -07:00
Josh Junon
f0c0178d12 Allow multiple arguments in base chalk object (fixes #187) 2017-08-06 18:58:17 -07:00
Josh Junon
0827d3b632 Fix level when supportsColor returns falsey (fixes #176, #175) 2017-08-06 18:58:17 -07:00
Josh Junon
fbd17e7a69 Escape backslashes in template arguments (fixes #177) 2017-08-06 18:58:17 -07:00
Josh Junon
7a75399b72 Add failing template tests 2017-08-06 18:58:17 -07:00
Boris K
7dbd8c3993 Add related packages in the readme (#193)
Added chalk-animation as suggested by @sindresorhus
Added gradient-string because it also uses chalk and provides new features.
2017-08-02 01:41:35 +02:00
Sindre Sorhus
4c4ba2df3d Fix template literal test 2017-07-23 22:24:56 +02:00
Kevin Mårtensson
4c4eb1fd0a Move testing to ava (#182) 2017-07-23 22:17:33 +02:00
Kevin Mårtensson
e8d28f3041 Return empty string when there are no arguments (#183) 2017-07-23 22:13:55 +02:00
Vadim Demedes
5cdd9eddf8 Demonstrate crash when using Truecolor methods and color is unsupported (#174) 2017-07-22 00:03:49 +02:00
Josh Junon
23092eefd2 add note about brightBlack (ref chalk/ansi-styles#33) 2017-07-07 16:03:36 -07:00
Sindre Sorhus
8d26c1401c Minor meta tweaks 2017-06-30 17:19:57 +02:00
Sindre Sorhus
5ec90cb354 Link to v2 release notes 2017-06-30 12:53:46 +02:00
Sindre Sorhus
3d10f8fad7 Code style tweaks 2017-06-30 12:42:24 +02:00
Josh Junon
5827081719 2.0.1 2017-06-29 20:26:07 -07:00
Josh Junon
caeb7d8dca fix missing TERM cases 2017-06-29 20:11:09 -07:00
Sindre Sorhus
3fca6150e2 2.0.0 2017-06-30 01:49:18 +02:00
Josh Junon
f66271e01a Add tagged template literal (#163) 2017-06-30 01:46:19 +02:00
Josh Junon
23ef1c7ca2 fix linter errors 2017-06-29 16:05:28 -07:00
Josh Junon
c0155688cf add rainbow example 2017-06-29 16:00:51 -07:00
Josh Junon
09fb2d8606 Re-implement chalk.enabled (#160) 2017-06-29 22:34:00 +02:00
Josh Junon
608242a4fc spoof supports-color 2017-06-29 00:01:36 -07:00
Josh Junon
18f2e7c122 add host information output 2017-06-29 00:01:36 -07:00
Josh Junon
523b998e64 Revert "TEMPORARY: emergency travis CI fix (see comments)"
This reverts commit 54975fb20d.
2017-06-29 00:01:19 -07:00
Josh Junon
54975fb20d TEMPORARY: emergency travis CI fix (see comments) 2017-06-28 23:42:38 -07:00
Sindre Sorhus
1d73b21111 Improve readme 2017-06-20 22:17:27 +02:00
Sindre Sorhus
6f4d6b30fb Bump dependencies 2017-06-20 21:38:49 +02:00
Sindre Sorhus
870249689a Remove chalk.styles
Very few consumers use this. Those who need it can just use the `ansi-styles` package directly.
2017-06-20 21:37:29 +02:00
Sindre Sorhus
0412cdf07b Minor code improvements 2017-06-20 21:17:16 +02:00
Sindre Sorhus
249b9ac7e7 ES2015ify the codebase 2017-06-20 19:21:14 +02:00
Josh Junon
cb3f2308e1 Add RGB (256/Truecolor) support (#140) 2017-06-20 19:02:09 +02:00
Haroen Viaene
dbae68d623 Update dependent package count in the readme (#154) 2017-05-31 16:55:22 +07:00
Sindre Sorhus
9b60021fa6 Drop support for Node.js 0.10 and 0.12 2017-05-21 23:28:38 +07:00
Josh
0d2144904b check parent builder object for enabled status (#142) 2017-01-30 04:10:02 -05:00
Sindre Sorhus
5a69476142 add XO badge 2016-10-26 20:13:45 +07:00
Sindre Sorhus
492f11fb59 add example file 2016-10-26 13:00:12 +07:00
Sindre Sorhus
4ce73b632b make XO happy 2016-10-17 23:50:22 +07:00
Josh Junon
7c02cf45f8 Add log statement to chalk examples (#129)
* Add log statement to chalk examples

Added what are essentially `console.log()` calls to the chalk examples.

Closes #128.

* Update readme.md
2016-09-08 17:12:05 +07:00
Popey Gilbert
835ca3d950 You've just reached 10,000 dependent modules. (#122)
* You've just reached 10,000 dependent modules.

* Update readme.md
2016-08-03 22:43:03 +02:00
Sakthipriyan Vairamani
74c087db82 minor doc improvements (#120)
* minor doc improvements

* address review comments
2016-07-26 23:13:15 -07:00
Sindre Sorhus
d939a3f9bc fix XO lint issue 2016-06-16 14:36:05 +02:00
Sindre Sorhus
a125eb0e72 OS X → macOS 2016-06-14 18:20:49 +02:00
Sindre Sorhus
6c3e57351b test on Node.js 6 2016-05-02 15:36:40 +07:00
Sindre Sorhus
fe2e4b093e update code of conduct 2016-05-02 15:36:24 +07:00
Sindre Sorhus
2653218312 meta tweaks 2016-04-06 23:05:21 +07:00
Josh Junon
ff2c3ea9a5 Merge pull request #104 from popey456963/patch-1
7,700 Dependent Modules
2016-03-15 14:29:36 -07:00
Popey Gilbert
426fc485bd 7,700 Dependent Modules
Yet another 1,000 modules in only two months.  That's almost a project an hour now using Chalk!
2016-03-15 20:18:41 +00:00
Joshua Boy Nicolai Appelman
9001b3933a Updates maintainer email. 2016-02-21 13:14:22 +01:00
Sindre Sorhus
308f6b6a1e minor tweaks 2016-01-17 12:44:51 +01:00
Sindre Sorhus
18c64ad7ba cleanup #92 2016-01-17 12:38:10 +01:00
Martin Heidegger
05f87e25e1 Close #92 PR: Closing before and reopening the style after a line break. 2016-01-17 12:35:27 +01:00
Sindre Sorhus
139f8b68cc add Code of Conduct 2016-01-15 00:06:24 +01:00
Josh Junon
51b8f329e8 6700 dependents! 🔥 2016-01-11 03:48:13 -07:00
Steve Mao
8417f175ab Close #95 PR: tweak defining proto. 2016-01-09 16:20:22 +01:00
Sindre Sorhus
a301cbf3d1 Merge pull request #97 from stevemao/missing-tests
add missing tests
2016-01-06 20:29:59 +01:00
Sindre Sorhus
8ec46cfb35 Merge pull request #96 from stevemao/bump-deps
bump deps
2016-01-06 20:29:00 +01:00
Steve Mao
337f9c7485 add missing tests 2016-01-06 19:06:51 +11:00
Steve Mao
5679ec0c04 bump deps
No breaking changes to this modules.
2016-01-06 19:00:34 +11:00
Sindre Sorhus
b8e7da6367 Merge pull request #93 from venning/master
Use HTTPS for shields.io unicorn badge
2015-12-31 21:45:28 +01:00
Christopher Venning
7c40059a03 Use HTTPS for shields.io unicorn badge; raises mixed-content warning on npmjs.com 2015-12-31 15:28:46 -05:00
Sindre Sorhus
c2ef5b8c13 Merge pull request #91 from vdemedes/remove-extra-deps
Remove has-ansi and strip-ansi dependencies
2015-12-12 23:58:26 +01:00
vdemedes
04cae226cc remove has-ansi and strip-ansi dependencies 2015-12-12 23:55:01 +01:00
Sindre Sorhus
83615f2ed6 clarify docs about using console.log
fixes #89
2015-11-05 13:12:34 +07:00
Edvin Erikson
ed6e7d56da Close #86 PR: Add ES2015 template literal example. Fixes #77 2015-10-09 01:10:28 +07:00
Sindre Sorhus
8d599972ee readme tweaks 2015-10-05 22:36:32 +07:00
Sindre Sorhus
262274af86 add slice-ansi to related section in readme 2015-09-26 15:15:59 +07:00
Josh Ballard
60b0a74adc Merge pull request #85 from jorrit/patch-1
new URL for cmder
2015-09-13 14:22:33 -06:00
Jorrit Schippers
641ae571b4 New URL for cmder 2015-09-13 22:19:40 +02:00
Qix
14603cd0f5 5000 dependents 🎊 2015-08-23 17:33:33 -06:00
Sindre Sorhus
8b554e254e 1.1.1 2015-08-20 03:10:52 +07:00
Sindre Sorhus
409f95eef5 add XO
https://github.com/sindresorhus/xo
2015-08-20 03:05:43 +07:00
Sindre Sorhus
fb6332df4f readme - add wrap-ansi to related section 2015-08-20 03:02:09 +07:00
Sindre Sorhus
5d2cefc243 Merge pull request #81 from lukeapage/master
Remove un-necessary function name. Fixes #80
2015-08-20 02:57:56 +07:00
Luke Page
4006cc0b41 Remove un-necessary function name. Fixes #80 2015-08-19 16:57:06 +01:00
Qix
6142553bb5 updated # of dependents to ~4.5k 2015-07-16 14:34:28 -06:00
Sindre Sorhus
789a0118c6 Merge pull request #74 from danielhusar/patch-1
Fix typo in readme
2015-07-03 15:19:32 +02:00
Daniel Husar
388e21aed7 Fix typo in readme 2015-07-03 14:16:30 +01:00
Qix
d7537f37df Merge branch 'master' of https://github.com/sindresorhus/chalk 2015-07-01 07:32:36 -06:00
Qix
632bd4a088 added Qix as maintainer 2015-07-01 07:32:17 -06:00
36 changed files with 2247 additions and 478 deletions

View file

@ -7,9 +7,6 @@ charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[package.json]
[*.yml]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

2
.gitattributes vendored
View file

@ -1 +1 @@
* text=auto
* text=auto eol=lf

4
.github/funding.yml vendored Normal file
View file

@ -0,0 +1,4 @@
github: [sindresorhus, Qix-]
open_collective: sindresorhus
tidelift: npm/chalk
custom: https://sindresorhus.com/donate

3
.github/security.md vendored Normal file
View file

@ -0,0 +1,3 @@
# Security Policy
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.

26
.github/workflows/main.yml vendored Normal file
View 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

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules
yarn.lock
coverage
.nyc_output

View file

@ -1,13 +0,0 @@
{
"node": true,
"esnext": true,
"bitwise": true,
"camelcase": true,
"curly": true,
"immed": true,
"newcap": true,
"noarg": true,
"undef": true,
"unused": "vars",
"strict": true
}

1
.npmrc Normal file
View file

@ -0,0 +1 @@
package-lock=false

View file

@ -1,7 +0,0 @@
sudo: false
language: node_js
node_js:
- 'iojs'
- '0.12'
- '0.10'
after_success: npm run coveralls

View file

@ -1,22 +1,57 @@
var chalk = require('./');
/* globals suite, bench */
import chalk from './index.js';
suite('chalk', function () {
set('iterations', 100000);
suite('chalk', () => {
const chalkRed = chalk.red;
const chalkBgRed = chalk.bgRed;
const chalkBlueBgRed = chalk.blue.bgRed;
const chalkBlueBgRedBold = chalk.blue.bgRed.bold;
bench('single style', function () {
const blueStyledString = 'the fox jumps' + chalk.blue('over the lazy dog') + '!';
bench('1 style', () => {
chalk.red('the fox jumps over the lazy dog');
});
bench('several styles', function () {
bench('2 styles', () => {
chalk.blue.bgRed('the fox jumps over the lazy dog');
});
bench('3 styles', () => {
chalk.blue.bgRed.bold('the fox jumps over the lazy dog');
});
var cached = chalk.blue.bgRed.bold;
bench('cached styles', function () {
cached('the fox jumps over the lazy dog');
bench('cached: 1 style', () => {
chalkRed('the fox jumps over the lazy dog');
});
bench('nested styles', function () {
chalk.red('the fox jumps', chalk.underline.bgBlue('over the lazy dog') + '!');
bench('cached: 2 styles', () => {
chalkBlueBgRed('the fox jumps over the lazy dog');
});
bench('cached: 3 styles', () => {
chalkBlueBgRedBold('the fox jumps over the lazy dog');
});
bench('cached: 1 style with newline', () => {
chalkRed('the fox jumps\nover the lazy dog');
});
bench('cached: 1 style nested intersecting', () => {
chalkRed(blueStyledString);
});
bench('cached: 1 style nested non-intersecting', () => {
chalkBgRed(blueStyledString);
});
bench('cached: 1 style template literal', () => {
// eslint-disable-next-line no-unused-expressions
chalkRed`the fox jumps over the lazy dog`;
});
bench('cached: nested styles template literal', () => {
// eslint-disable-next-line no-unused-expressions
chalkRed`the fox {bold jumps} over the {underline lazy} dog`;
});
});

74
code-of-conduct.md Normal file
View file

@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at sindresorhus@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

3
contributing.md Normal file
View file

@ -0,0 +1,3 @@
# Contributing to Chalk
Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms.

38
examples/rainbow.js Normal file
View file

@ -0,0 +1,38 @@
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;
function rainbow(string, offset) {
if (!string || string.length === 0) {
return string;
}
const hueStep = 360 / string.replaceAll(ignoreChars, '').length;
let hue = offset % 360;
const characters = [];
for (const character of string) {
if (ignoreChars.test(character)) {
characters.push(character);
} else {
characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character));
hue = (hue + hueStep) % 360;
}
}
return characters.join('');
}
async function animateString(string) {
for (let index = 0; index < 360 * 5; index++) {
updateLog(rainbow(string, index));
await delay(2); // eslint-disable-line no-await-in-loop
}
}
console.log();
await animateString('We hope you enjoy Chalk! <3');
console.log();

27
examples/screenshot.js Normal file
View file

@ -0,0 +1,27 @@
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;
// 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;
}
if (/^bg[^B]/.test(key)) {
returnValue = chalk.black(returnValue);
}
process.stdout.write(chalk[key](returnValue) + ' ');
}

116
index.js
View file

@ -1,116 +0,0 @@
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var stripAnsi = require('strip-ansi');
var hasAnsi = require('has-ansi');
var supportsColor = require('supports-color');
var defineProps = Object.defineProperties;
var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
function Chalk(options) {
// detect mode if not set manually
this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
}
// use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001b[94m';
}
var styles = (function () {
var ret = {};
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build.call(this, this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function chalk() {}, styles);
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder.enabled = this.enabled;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
/*eslint no-proto: 0 */
builder.__proto__ = proto;
return builder;
}
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// don't slice `arguments`, it prevents v8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
ansiStyles.dim.open = '';
}
while (i--) {
var code = ansiStyles[nestedStyles[i]];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
ansiStyles.dim.open = originalDim;
return str;
}
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build.call(this, [name]);
}
};
});
return ret;
}
defineProps(Chalk.prototype, init());
module.exports = new Chalk();
module.exports.styles = ansiStyles;
module.exports.hasColor = hasAnsi;
module.exports.stripColor = stripAnsi;
module.exports.supportsColor = supportsColor;

22
license
View file

@ -1,21 +1,9 @@
The MIT License (MIT)
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:
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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

BIN
media/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

View file

@ -1,62 +1,83 @@
{
"name": "chalk",
"version": "1.1.0",
"description": "Terminal string styling done right. Much color.",
"license": "MIT",
"repository": "chalk/chalk",
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Appelman <jappelman@xebia.com> (jbnicolai.com)"
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha",
"bench": "matcha benchmark.js",
"coverage": "nyc npm test && nyc report",
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^2.1.0",
"escape-string-regexp": "^1.0.2",
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
},
"devDependencies": {
"coveralls": "^2.11.2",
"matcha": "^0.6.0",
"mocha": "*",
"nyc": "^3.0.0",
"require-uncached": "^1.0.2",
"resolve-from": "^1.0.0",
"semver": "^4.3.3"
}
"name": "chalk",
"version": "5.6.2",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"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": "^12.17.0 || ^14.13 || >=16.0.0"
},
"scripts": {
"test": "xo && c8 ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"source",
"!source/index.test-d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"@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",
"tsd": "^0.19.0",
"xo": "^0.57.0",
"yoctodelay": "^2.0.0"
},
"xo": {
"rules": {
"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": {
"reporter": [
"text",
"lcov"
],
"exclude": [
"source/vendor"
]
}
}

269
readme.md
View file

@ -1,7 +1,7 @@
<h1 align="center">
<br>
<br>
<img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
@ -9,83 +9,105 @@
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
[![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)
![](media/screenshot.png)
[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). Although there are other ones, they either do too much or not enough.
## Info
**Chalk is a clean and focused alternative.**
- [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
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Highlights
## Why
- Highly performant
- Doesn't extend `String.prototype`
- Expressive API
- Highly performant
- No dependencies
- Ability to nest styles
- Clean and focused
- [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 ~4000 modules](https://www.npmjs.com/browse/depended/chalk) as of May 24, 2015
- [Used by ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024
## Install
```
$ npm install --save 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
import chalk from 'chalk';
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
var chalk = require('chalk');
import chalk from 'chalk';
// style a string
chalk.blue('Hello world!');
const log = console.log;
// combine styled and normal strings
chalk.blue('Hello') + 'World' + chalk.red('!');
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// compose multiple styles using the chainable API
chalk.blue.bgRed.bold('Hello world!');
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// pass in multiple arguments
chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// nest styles
chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// nest styles of the same type even (color, underline, background)
chalk.green(
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
);
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes.
Easily define your own themes:
```js
var chalk = require('chalk');
var error = chalk.bold.red;
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange color
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
var name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> Hello Sindre
```
import chalk from 'chalk';
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
@ -93,75 +115,73 @@ console.log(chalk.green('Hello %s'), name);
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and 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`.
Chain [styles](#styles) and 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`.
Multiple arguments will be separated by space.
### chalk.enabled
### chalk.level
Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
Specifies the level of color support.
If you need to change this in a reusable module create a new instance:
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
var ctx = new chalk.constructor({enabled: false});
import {Chalk} from 'chalk';
const customChalk = new Chalk({level: 0});
```
### chalk.supportsColor
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
### chalk.styles
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
### chalkStderr and supportsColorStderr
Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
`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
var chalk = require('chalk');
import {modifierNames, foregroundColorNames} from 'chalk';
console.log(chalk.styles.red);
//=> {open: '\u001b[31m', close: '\u001b[39m'}
console.log(modifierNames.includes('bold'));
//=> true
console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
console.log(foregroundColorNames.includes('pink'));
//=> false
```
### chalk.hasColor(string)
Check whether a string [has color](https://github.com/chalk/has-ansi).
### chalk.stripColor(string)
[Strip color](https://github.com/chalk/strip-ansi) from a string.
Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
Example:
```js
var chalk = require('chalk');
var styledString = getText();
if (!chalk.supportsColor) {
styledString = chalk.stripColor(styledString);
}
```
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
- `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` - Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.
### Colors
@ -169,11 +189,18 @@ if (!chalk.supportsColor) {
- `red`
- `green`
- `yellow`
- `blue` *(on Windows the bright version is used as normal blue is illegible)*
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
@ -185,28 +212,86 @@ if (!chalk.supportsColor) {
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## 256 and Truecolor color support
## 256-colors
Chalk supports 256 colors and [Truecolor](https://github.com/termstandard/colors) (16 million colors) on supported terminal apps.
Chalk does not support support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
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.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. `hex` for foreground colors and `bgHex` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `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!')`
- [`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 [`cmder`](http://bliker.github.io/cmder/) 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`.
## FAQ
### Why not switch to a smaller coloring package?
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.
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.
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
- [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
- [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
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to 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
*(Not accepting additional entries)*
## License
## Maintainers
MIT © [Sindre Sorhus](http://sindresorhus.com)
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

325
source/index.d.ts vendored Normal file
View 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;

225
source/index.js Normal file
View file

@ -0,0 +1,225 @@
import ansiStyles from '#ansi-styles';
import supportsColor from '#supports-color';
import { // eslint-disable-line import/order
stringReplaceAll,
stringEncaseCRLFWithFirstIndex,
} from './utilities.js';
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',
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
// Detect level if not set manually
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
};
export class Chalk {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = (...strings) => strings.join(' ');
applyOptions(chalk, options);
Object.setPrototypeOf(chalk, createChalk.prototype);
return chalk;
};
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[IS_EMPTY]);
Object.defineProperty(this, styleName, {value: builder});
return builder;
},
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, 'visible', {value: builder});
return builder;
},
};
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(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
}
const proto = Object.defineProperties(() => {}, {
...styles,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
},
},
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === undefined) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent,
};
};
const createBuilder = (self, _styler, _isEmpty) => {
// 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[IS_EMPTY] = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self[IS_EMPTY] ? '' : string;
}
let styler = self[STYLER];
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
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
// will be colored, and the rest will simply be 'plain'.
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
// We can move both next actions out of loop, because remaining actions in loop won't have
// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles);
const chalk = createChalk();
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 {
stdoutColor as supportsColor,
stderrColor as supportsColorStderr,
};
export default chalk;

179
source/index.test-d.ts Normal file
View file

@ -0,0 +1,179 @@
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<ColorInfo>(supportsColor);
if (supportsColor) {
expectType<ColorSupport>(supportsColor);
expectType<ColorSupportLevel>(supportsColor.level);
expectType<boolean>(supportsColor.hasBasic);
expectType<boolean>(supportsColor.has256);
expectType<boolean>(supportsColor.has16m);
}
// - stderr -
expectAssignable<ChalkInstance>(chalkStderr);
expectType<ColorInfo>(supportsColorStderr);
if (supportsColorStderr) {
expectType<boolean>(supportsColorStderr.hasBasic);
expectType<boolean>(supportsColorStderr.has256);
expectType<boolean>(supportsColorStderr.has16m);
}
// -- `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<ChalkInstance>(new Chalk({level: 1}));
// -- Properties --
expectType<ColorSupportLevel>(chalk.level);
// -- Color methods --
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'));
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'));
expectType<string>(chalk.visible('foo'));
expectType<string>(chalk.reset`foo`);
expectType<string>(chalk.bold`foo`);
expectType<string>(chalk.dim`foo`);
expectType<string>(chalk.italic`foo`);
expectType<string>(chalk.underline`foo`);
expectType<string>(chalk.inverse`foo`);
expectType<string>(chalk.hidden`foo`);
expectType<string>(chalk.strikethrough`foo`);
expectType<string>(chalk.visible`foo`);
// -- Colors --
expectType<string>(chalk.black('foo'));
expectType<string>(chalk.red('foo'));
expectType<string>(chalk.green('foo'));
expectType<string>(chalk.yellow('foo'));
expectType<string>(chalk.blue('foo'));
expectType<string>(chalk.magenta('foo'));
expectType<string>(chalk.cyan('foo'));
expectType<string>(chalk.white('foo'));
expectType<string>(chalk.gray('foo'));
expectType<string>(chalk.grey('foo'));
expectType<string>(chalk.blackBright('foo'));
expectType<string>(chalk.redBright('foo'));
expectType<string>(chalk.greenBright('foo'));
expectType<string>(chalk.yellowBright('foo'));
expectType<string>(chalk.blueBright('foo'));
expectType<string>(chalk.magentaBright('foo'));
expectType<string>(chalk.cyanBright('foo'));
expectType<string>(chalk.whiteBright('foo'));
expectType<string>(chalk.bgBlack('foo'));
expectType<string>(chalk.bgRed('foo'));
expectType<string>(chalk.bgGreen('foo'));
expectType<string>(chalk.bgYellow('foo'));
expectType<string>(chalk.bgBlue('foo'));
expectType<string>(chalk.bgMagenta('foo'));
expectType<string>(chalk.bgCyan('foo'));
expectType<string>(chalk.bgWhite('foo'));
expectType<string>(chalk.bgBlackBright('foo'));
expectType<string>(chalk.bgRedBright('foo'));
expectType<string>(chalk.bgGreenBright('foo'));
expectType<string>(chalk.bgYellowBright('foo'));
expectType<string>(chalk.bgBlueBright('foo'));
expectType<string>(chalk.bgMagentaBright('foo'));
expectType<string>(chalk.bgCyanBright('foo'));
expectType<string>(chalk.bgWhiteBright('foo'));
expectType<string>(chalk.black`foo`);
expectType<string>(chalk.red`foo`);
expectType<string>(chalk.green`foo`);
expectType<string>(chalk.yellow`foo`);
expectType<string>(chalk.blue`foo`);
expectType<string>(chalk.magenta`foo`);
expectType<string>(chalk.cyan`foo`);
expectType<string>(chalk.white`foo`);
expectType<string>(chalk.gray`foo`);
expectType<string>(chalk.grey`foo`);
expectType<string>(chalk.blackBright`foo`);
expectType<string>(chalk.redBright`foo`);
expectType<string>(chalk.greenBright`foo`);
expectType<string>(chalk.yellowBright`foo`);
expectType<string>(chalk.blueBright`foo`);
expectType<string>(chalk.magentaBright`foo`);
expectType<string>(chalk.cyanBright`foo`);
expectType<string>(chalk.whiteBright`foo`);
expectType<string>(chalk.bgBlack`foo`);
expectType<string>(chalk.bgRed`foo`);
expectType<string>(chalk.bgGreen`foo`);
expectType<string>(chalk.bgYellow`foo`);
expectType<string>(chalk.bgBlue`foo`);
expectType<string>(chalk.bgMagenta`foo`);
expectType<string>(chalk.bgCyan`foo`);
expectType<string>(chalk.bgWhite`foo`);
expectType<string>(chalk.bgBlackBright`foo`);
expectType<string>(chalk.bgRedBright`foo`);
expectType<string>(chalk.bgGreenBright`foo`);
expectType<string>(chalk.bgYellowBright`foo`);
expectType<string>(chalk.bgBlueBright`foo`);
expectType<string>(chalk.bgMagentaBright`foo`);
expectType<string>(chalk.bgCyanBright`foo`);
expectType<string>(chalk.bgWhiteBright`foo`);
// -- Complex --
expectType<string>(chalk.red.bgGreen.underline('foo'));
expectType<string>(chalk.underline.red.bgGreen('foo'));
// -- Complex template literal --
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}}`);
// -- 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');

33
source/utilities.js Normal file
View 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
View 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
View 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;

View file

@ -0,0 +1 @@
export {default} from './index.js';

34
source/vendor/supports-color/browser.js vendored Normal file
View 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
View 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
View 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;

158
test.js
View file

@ -1,158 +0,0 @@
'use strict';
var assert = require('assert');
var requireUncached = require('require-uncached');
var resolveFrom = require('resolve-from');
var semver = require('semver');
var chalk = require('./');
describe('chalk', function () {
it('should style string', function () {
assert.equal(chalk.underline('foo'), '\u001b[4mfoo\u001b[24m');
assert.equal(chalk.red('foo'), '\u001b[31mfoo\u001b[39m');
assert.equal(chalk.bgRed('foo'), '\u001b[41mfoo\u001b[49m');
});
it('should support applying multiple styles at once', function () {
assert.equal(chalk.red.bgGreen.underline('foo'), '\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39m');
assert.equal(chalk.underline.red.bgGreen('foo'), '\u001b[4m\u001b[31m\u001b[42mfoo\u001b[49m\u001b[39m\u001b[24m');
});
it('should support nesting styles', function () {
assert.equal(
chalk.red('foo' + chalk.underline.bgBlue('bar') + '!'),
'\u001b[31mfoo\u001b[4m\u001b[44mbar\u001b[49m\u001b[24m!\u001b[39m'
);
});
it('should support nesting styles of the same type (color, underline, bg)', function () {
assert.equal(
chalk.red('a' + chalk.yellow('b' + chalk.green('c') + 'b') + 'c'),
'\u001b[31ma\u001b[33mb\u001b[32mc\u001b[33mb\u001b[31mc\u001b[39m'
);
});
it('should reset all styles with `.reset()`', function () {
assert.equal(chalk.reset(chalk.red.bgGreen.underline('foo') + 'foo'), '\u001b[0m\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39mfoo\u001b[0m');
});
it('should be able to cache multiple styles', function () {
var red = chalk.red;
var green = chalk.green;
var redBold = red.bold;
var greenBold = green.bold;
assert.notEqual(red('foo'), green('foo'));
assert.notEqual(redBold('bar'), greenBold('bar'));
assert.notEqual(green('baz'), greenBold('baz'));
});
it('should alias gray to grey', function () {
assert.equal(chalk.grey('foo'), '\u001b[90mfoo\u001b[39m');
});
it('should support variable number of arguments', function () {
assert.equal(chalk.red('foo', 'bar'), '\u001b[31mfoo bar\u001b[39m');
});
it('should support falsy values', function () {
assert.equal(chalk.red(0), '\u001b[31m0\u001b[39m');
});
it('don\'t output escape codes if the input is empty', function () {
assert.equal(chalk.red(), '');
});
});
describe('chalk on windows', function () {
var originalEnv;
var originalPlatform;
// in node versions older than 0.12.x process.platform cannot be overridden
if (semver.lt(process.version, '0.12.0')) {
return;
}
before(function () {
originalEnv = process.env;
originalPlatform = process.platform;
});
after(function () {
process.env = originalEnv;
Object.defineProperty(process, 'platform', {value: originalPlatform});
});
beforeEach(function () {
process.env = {};
Object.defineProperty(process, 'platform', {value: 'win32'});
// since chalk internally modifies ansiStyles.blue.open, ansi-styles needs
// to be removed from the require cache for require-uncached to work
delete require.cache[resolveFrom(__dirname, 'ansi-styles')];
});
it('should replace blue foreground color in cmd.exe', function () {
process.env.TERM = 'dumb';
var chalkCtx = requireUncached('./');
assert.equal(chalkCtx.blue('foo'), '\u001b[94mfoo\u001b[39m');
});
it('shouldn\'t replace blue foreground color in xterm based terminals', function () {
process.env.TERM = 'xterm-256color';
var chalkCtx = requireUncached('./');
assert.equal(chalkCtx.blue('foo'), '\u001b[34mfoo\u001b[39m');
});
it('should not apply dimmed styling on gray strings, see https://github.com/chalk/chalk/issues/58', function () {
process.env.TERM = 'dumb';
var chalkCtx = requireUncached('./');
assert.equal(chalkCtx.gray.dim('foo'), '\u001b[90mfoo\u001b[22m\u001b[39m');
});
it('should apply dimmed styling on xterm compatible terminals', function () {
process.env.TERM = 'xterm';
var chalkCtx = requireUncached('./');
assert.equal(chalkCtx.gray.dim('foo'), '\u001b[90m\u001b[2mfoo\u001b[22m\u001b[39m');
});
it('should apply dimmed styling on strings of other colors', function () {
process.env.TERM = 'dumb';
var chalkCtx = requireUncached('./');
assert.equal(chalkCtx.blue.dim('foo'), '\u001b[94m\u001b[2mfoo\u001b[22m\u001b[39m');
});
});
describe('chalk.enabled', function () {
it('should not output colors when manually disabled', function () {
chalk.enabled = false;
assert.equal(chalk.red('foo'), 'foo');
chalk.enabled = true;
});
});
describe('chalk.constructor', function () {
it('should create a isolated context where colors can be disabled', function () {
var ctx = new chalk.constructor({enabled: false});
assert.equal(ctx.red('foo'), 'foo');
assert.equal(chalk.red('foo'), '\u001b[31mfoo\u001b[39m');
});
});
describe('chalk.styles', function () {
it('should expose the styles as ANSI escape codes', function () {
assert.equal(chalk.styles.red.open, '\u001b[31m');
});
});
describe('chalk.hasColor()', function () {
it('should detect whether a string has color', function () {
assert(chalk.hasColor(chalk.green('foo')));
assert(!chalk.hasColor(chalk.stripColor(chalk.green('foo'))));
});
});
describe('chalk.stripColor()', function () {
it('should strip color from string', function () {
assert.equal(chalk.stripColor(chalk.underline.red.bgGreen('foo')), 'foo');
});
});

3
test/_fixture.js Normal file
View file

@ -0,0 +1,3 @@
import chalk, {chalkStderr} from '../source/index.js';
console.log(`${chalk.hex('#ff6159')('testout')} ${chalkStderr.hex('#ff6159')('testerr')}`);

126
test/chalk.js Normal file
View file

@ -0,0 +1,126 @@
import process from 'node:process';
import test from 'ava';
import chalk, {Chalk, chalkStderr} from '../source/index.js';
chalk.level = 3;
chalkStderr.level = 3;
console.log('TERM:', process.env.TERM || '[none]');
console.log('platform:', process.platform || '[unknown]');
test('don\'t add any styling when called as the base function', t => {
t.is(chalk('foo'), 'foo');
});
test('support multiple arguments in base function', t => {
t.is(chalk('hello', 'there'), 'hello there');
});
test('support automatic casting to string', t => {
t.is(chalk(['hello', 'there']), 'hello,there');
t.is(chalk(123), '123');
t.is(chalk.bold(['foo', 'bar']), '\u001B[1mfoo,bar\u001B[22m');
t.is(chalk.green(98_765), '\u001B[32m98765\u001B[39m');
});
test('style string', t => {
t.is(chalk.underline('foo'), '\u001B[4mfoo\u001B[24m');
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(chalk.bgRed('foo'), '\u001B[41mfoo\u001B[49m');
});
test('support applying multiple styles at once', t => {
t.is(chalk.red.bgGreen.underline('foo'), '\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39m');
t.is(chalk.underline.red.bgGreen('foo'), '\u001B[4m\u001B[31m\u001B[42mfoo\u001B[49m\u001B[39m\u001B[24m');
});
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',
);
});
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',
);
});
test('reset all styles with `.reset()`', t => {
t.is(chalk.reset(chalk.red.bgGreen.underline('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
});
test('support caching multiple styles', t => {
const {red, green} = chalk.red;
const redBold = red.bold;
const greenBold = green.bold;
t.not(red('foo'), green('foo'));
t.not(redBold('bar'), greenBold('bar'));
t.not(green('baz'), greenBold('baz'));
});
test('alias gray to grey', t => {
t.is(chalk.grey('foo'), '\u001B[90mfoo\u001B[39m');
});
test('support variable number of arguments', t => {
t.is(chalk.red('foo', 'bar'), '\u001B[31mfoo bar\u001B[39m');
});
test('support falsy values', t => {
t.is(chalk.red(0), '\u001B[31m0\u001B[39m');
});
test('don\'t output escape codes if the input is empty', t => {
t.is(chalk.red(), '');
t.is(chalk.red.blue.black(), '');
});
test('keep Function.prototype methods', t => {
t.is(Reflect.apply(chalk.grey, null, ['foo']), '\u001B[90mfoo\u001B[39m');
t.is(chalk.reset(chalk.red.bgGreen.underline.bind(null)('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
t.is(chalk.red.blue.black.call(null), '');
});
test('line breaks should open and close colors', t => {
t.is(chalk.grey('hello\nworld'), '\u001B[90mhello\u001B[39m\n\u001B[90mworld\u001B[39m');
});
test('line breaks should open and close colors with CRLF', t => {
t.is(chalk.grey('hello\r\nworld'), '\u001B[90mhello\u001B[39m\r\n\u001B[90mworld\u001B[39m');
});
test('properly convert RGB to 16 colors on basic color terminals', t => {
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({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({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 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');
});

24
test/instance.js Normal file
View file

@ -0,0 +1,24 @@
import test from 'ava';
import chalk, {Chalk} from '../source/index.js';
chalk.level = 1;
test('create an isolated context where colors can be disabled (by level)', t => {
const instance = new Chalk({level: 0});
t.is(instance.red('foo'), 'foo');
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
instance.level = 2;
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
});
test('the `level` option should be a number from 0 to 3', t => {
/* eslint-disable no-new */
t.throws(() => {
new Chalk({level: 10});
}, {message: /should be an integer from 0 to 3/});
t.throws(() => {
new Chalk({level: -1});
}, {message: /should be an integer from 0 to 3/});
/* eslint-enable no-new */
});

43
test/level.js Normal file
View file

@ -0,0 +1,43 @@
import {fileURLToPath} from 'node:url';
import test from 'ava';
import {execaNode} from 'execa';
import chalk from '../source/index.js';
chalk.level = 1;
test('don\'t output colors when manually disabled', t => {
const oldLevel = chalk.level;
chalk.level = 0;
t.is(chalk.red('foo'), 'foo');
chalk.level = oldLevel;
});
test('enable/disable colors based on overall chalk .level property, not individual instances', t => {
const oldLevel = chalk.level;
chalk.level = 1;
const {red} = chalk;
t.is(red.level, 1);
chalk.level = 0;
t.is(red.level, chalk.level);
chalk.level = oldLevel;
});
test('propagate enable/disable changes from child colors', t => {
const oldLevel = chalk.level;
chalk.level = 1;
const {red} = chalk;
t.is(red.level, 1);
t.is(chalk.level, 1);
red.level = 0;
t.is(red.level, 0);
t.is(chalk.level, 0);
chalk.level = 1;
t.is(red.level, 1);
t.is(chalk.level, 1);
chalk.level = oldLevel;
});
test('disable colors if they are not supported', async t => {
const {stdout} = await execaNode(fileURLToPath(new URL('_fixture.js', import.meta.url)));
t.is(stdout, 'testout testerr');
});

24
test/no-color-support.js Normal file
View file

@ -0,0 +1,24 @@
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
// }
// });
test('colors can be forced by using chalk.level', t => {
chalk.level = 1;
t.is(chalk.green('hello'), '\u001B[32mhello\u001B[39m');
});

39
test/visible.js Normal file
View file

@ -0,0 +1,39 @@
import test from 'ava';
import chalk, {Chalk} from '../source/index.js';
chalk.level = 1;
test('visible: normal output when level > 0', t => {
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({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({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');
t.is(instance.visible('foo'), 'foo');
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
instance.level = 0;
t.is(instance.red('foo'), 'foo');
t.is(instance.visible('foo'), '');
t.is(instance.visible.red('foo'), '');
t.is(instance.red.visible('foo'), '');
t.is(instance.red('foo'), 'foo');
instance.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');
t.is(instance.visible('foo'), 'foo');
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
});