├── .github ├── demo.png ├── workflows │ ├── release.yml │ └── main.yml └── demo.ts ├── tsconfig.module.json ├── tools └── post-build.js ├── tsconfig.esm.json ├── tsconfig.json ├── .changeset ├── config.json └── README.md ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── .gitignore └── src ├── index.ts └── index.test.ts /.github/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marvinhagemeister/kolorist/HEAD/.github/demo.png -------------------------------------------------------------------------------- /tsconfig.module.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "ESNext", 5 | "target": "ES5", 6 | "outDir": "./dist/module/" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tools/post-build.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs'); 3 | 4 | const dir = path.join(__dirname, '..', 'dist', 'esm'); 5 | fs.copyFileSync(path.join(dir, 'index.js'), path.join(dir, 'index.mjs')); 6 | -------------------------------------------------------------------------------- /tsconfig.esm.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "ESNext", 5 | "declaration": true, 6 | "declarationDir": "./dist/types/", 7 | "outDir": "./dist/esm/" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "target": "ES2019", 5 | "module": "CommonJS", 6 | "moduleResolution": "node", 7 | "outDir": "dist/cjs/", 8 | "sourceMap": true, 9 | "allowJs": true 10 | }, 11 | "files": ["./src/index.ts"] 12 | } 13 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # kolorist 2 | 3 | ## 1.8.0 4 | 5 | ### Minor Changes 6 | 7 | - 737ef18: Add support for 24bit TrueColor detection. 8 | 9 | This is supported in nearly every modern terminals these days. The exception to that is the built in Terminal app on macOS and CI systems. TrueColor values are automatically converted to Ansi 256 when TrueColor isn't supported, but Ansi 256 is. The only case where I found that in practice was with Terminal.app on macOS which only supports Ansi 256. 10 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | name: Release 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - uses: actions/setup-node@v3 15 | with: 16 | node-version: 18 17 | - run: npm ci 18 | - name: Create Release Pull Request 19 | uses: changesets/action@v1 20 | env: 21 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 22 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | node-version: [14.x] 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | - name: Use Node.js ${{ matrix.node-version }} 15 | uses: actions/setup-node@v1 16 | with: 17 | node-version: ${{ matrix.node-version }} 18 | - name: Install 19 | run: npm ci 20 | - name: Test 21 | run: npm test 22 | -------------------------------------------------------------------------------- /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.github/demo.ts: -------------------------------------------------------------------------------- 1 | // npx ts-node-transpile-only .github/demo.ts 2 | import * as k from '../src/index'; 3 | 4 | const modifiers = ['reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough']; 5 | const colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray']; 6 | const lightColors = ['lightRed', 'lightGreen', 'lightYellow', 'lightBlue', 'lightMagenta', 'lightCyan', 'lightGray']; 7 | const bgColors = ['bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite', 'bgGray']; 8 | const bgLightColors = ['bgLightRed', 'bgLightGreen', 'bgLightYellow', 'bgLightBlue', 'bgLightMagenta', 'bgLightCyan']; 9 | 10 | console.log(modifiers.map(m => k[m](m)).join(' ')); 11 | console.log(colors.map(m => k[m](m)).join(' ')); 12 | console.log(lightColors.map(m => k[m](m)).join(' ')); 13 | console.log(bgColors.map(m => k[m](m)).join(' ')); 14 | console.log(bgLightColors.map(m => k[m](m)).join(' ')); 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020-present Marvin Hagemeister 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kolorist 2 | 3 | Tiny library to put colors into stdin/stdout :tada: 4 | 5 | ![Screenshot of terminal colors](.github/demo.png) 6 | 7 | ## Usage 8 | 9 | ```bash 10 | npm install --save-dev kolorist 11 | ``` 12 | 13 | ```js 14 | import { red, cyan } from 'kolorist'; 15 | 16 | console.log(red(`Error: something failed in ${cyan('my-file.js')}.`)); 17 | ``` 18 | 19 | You can also disable or enable colors globally via the following environment variables: 20 | 21 | - disable: 22 | - `NODE_DISABLE_COLORS` 23 | - `NO_COLOR` 24 | - `TERM=dumb` 25 | - `FORCE_COLOR=0` 26 | 27 | - enable: 28 | - `FORCE_COLOR=1` 29 | - `FORCE_COLOR=2` 30 | - `FORCE_COLOR=3` 31 | 32 | On top of that you can disable colors right from node: 33 | 34 | ```js 35 | import { options, red } from 'kolorist'; 36 | 37 | options.enabled = false; 38 | console.log(red('foo')); 39 | // Logs a string without colors 40 | ``` 41 | 42 | You can also strip colors from a string: 43 | 44 | ```js 45 | import { red, stripColors } from 'kolorist'; 46 | 47 | console.log(stripColors(red('foo'))); 48 | // Logs 'foo' 49 | ``` 50 | 51 | ### License 52 | 53 | `MIT`, see [the license file](./LICENSE). 54 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kolorist", 3 | "version": "1.8.0", 4 | "description": "A tiny utility to colorize stdin/stdout", 5 | "main": "dist/cjs/index.js", 6 | "module": "dist/module/index.js", 7 | "types": "dist/types/index.d.ts", 8 | "scripts": { 9 | "test": "mocha -r @esbuild-kit/cjs-loader --extension ts,js src/*.test.ts", 10 | "build": "rimraf dist/ && tsc && tsc -p tsconfig.module.json && tsc -p tsconfig.esm.json && node tools/post-build.js", 11 | "prepublishOnly": "npm run build" 12 | }, 13 | "author": "Marvin Hagemeister ", 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/marvinhagemeister/kolorist.git" 17 | }, 18 | "license": "MIT", 19 | "devDependencies": { 20 | "@changesets/cli": "^2.26.0", 21 | "@esbuild-kit/cjs-loader": "^2.4.1", 22 | "@types/mocha": "^8.2.1", 23 | "@types/node": "^14.14.35", 24 | "mocha": "^8.3.2", 25 | "node-pty": "^0.10.0", 26 | "prettier": "^2.2.1", 27 | "rimraf": "^3.0.2", 28 | "typescript": "^4.2.3" 29 | }, 30 | "exports": { 31 | ".": { 32 | "types": "./dist/types/index.d.ts", 33 | "browser": "./dist/module/index.js", 34 | "import": "./dist/esm/index.mjs", 35 | "require": "./dist/cjs/index.js" 36 | }, 37 | "./package.json": "./package.json", 38 | "./*": "./*" 39 | }, 40 | "files": [ 41 | "dist/" 42 | ], 43 | "prettier": { 44 | "useTabs": true, 45 | "arrowParens": "avoid", 46 | "singleQuote": true 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and not Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | # Stores VSCode versions used for testing VSCode extensions 107 | .vscode-test 108 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | let enabled = true; 2 | 3 | // Support both browser and node environments 4 | const globalVar = 5 | typeof self !== 'undefined' 6 | ? self 7 | : typeof window !== 'undefined' 8 | ? window 9 | : typeof global !== 'undefined' 10 | ? global 11 | : ({} as any); 12 | 13 | export const enum SupportLevel { 14 | none, 15 | ansi, 16 | ansi256, 17 | trueColor, 18 | } 19 | 20 | /** 21 | * Detect how much colors the current terminal supports 22 | */ 23 | let supportLevel: SupportLevel = SupportLevel.none; 24 | 25 | if (globalVar.process && globalVar.process.env && globalVar.process.stdout) { 26 | const { FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, COLORTERM } = 27 | globalVar.process.env; 28 | if (NODE_DISABLE_COLORS || NO_COLOR || FORCE_COLOR === '0') { 29 | enabled = false; 30 | } else if ( 31 | FORCE_COLOR === '1' || 32 | FORCE_COLOR === '2' || 33 | FORCE_COLOR === '3' 34 | ) { 35 | enabled = true; 36 | } else if (TERM === 'dumb') { 37 | enabled = false; 38 | } else if ( 39 | 'CI' in globalVar.process.env && 40 | [ 41 | 'TRAVIS', 42 | 'CIRCLECI', 43 | 'APPVEYOR', 44 | 'GITLAB_CI', 45 | 'GITHUB_ACTIONS', 46 | 'BUILDKITE', 47 | 'DRONE', 48 | ].some(vendor => vendor in globalVar.process.env) 49 | ) { 50 | enabled = true; 51 | } else { 52 | enabled = process.stdout.isTTY; 53 | } 54 | 55 | if (enabled) { 56 | // Windows supports 24bit True Colors since Windows 10 revision #14931, 57 | // see https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/ 58 | if (process.platform === 'win32') { 59 | supportLevel = SupportLevel.trueColor; 60 | } else { 61 | if (COLORTERM && (COLORTERM === 'truecolor' || COLORTERM === '24bit')) { 62 | supportLevel = SupportLevel.trueColor; 63 | } else if (TERM && (TERM.endsWith('-256color') || TERM.endsWith('256'))) { 64 | supportLevel = SupportLevel.ansi256; 65 | } else { 66 | supportLevel = SupportLevel.ansi; 67 | } 68 | } 69 | } 70 | } 71 | 72 | export let options = { 73 | enabled, 74 | supportLevel, 75 | }; 76 | 77 | /*@__NO_SIDE_EFFECTS__*/ 78 | function kolorist( 79 | start: number | string, 80 | end: number | string, 81 | level: SupportLevel = SupportLevel.ansi 82 | ) { 83 | const open = `\x1b[${start}m`; 84 | const close = `\x1b[${end}m`; 85 | const regex = new RegExp(`\\x1b\\[${end}m`, 'g'); 86 | 87 | return (str: string | number) => { 88 | return options.enabled && options.supportLevel >= level 89 | ? open + ('' + str).replace(regex, open) + close 90 | : '' + str; 91 | }; 92 | } 93 | 94 | // Lower colors into 256 color space 95 | // Taken from https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js 96 | // which is MIT licensed and copyright by Heather Arthur and Josh Junon 97 | function rgbToAnsi256(r: number, g: number, b: number): number { 98 | // We use the extended greyscale palette here, with the exception of 99 | // black and white. normal palette only has 4 greyscale shades. 100 | if (r >> 4 === g >> 4 && g >> 4 === b >> 4) { 101 | if (r < 8) { 102 | return 16; 103 | } 104 | 105 | if (r > 248) { 106 | return 231; 107 | } 108 | 109 | return Math.round(((r - 8) / 247) * 24) + 232; 110 | } 111 | 112 | const ansi = 113 | 16 + 114 | 36 * Math.round((r / 255) * 5) + 115 | 6 * Math.round((g / 255) * 5) + 116 | Math.round((b / 255) * 5); 117 | 118 | return ansi; 119 | } 120 | 121 | export function stripColors(str: string | number) { 122 | return ('' + str) 123 | .replace(/\x1b\[[0-9;]+m/g, '') 124 | .replace(/\x1b\]8;;.*?\x07(.*?)\x1b\]8;;\x07/g, (_, group) => group); 125 | } 126 | 127 | // modifiers 128 | export const reset = kolorist(0, 0); 129 | export const bold = kolorist(1, 22); 130 | export const dim = kolorist(2, 22); 131 | export const italic = kolorist(3, 23); 132 | export const underline = kolorist(4, 24); 133 | export const inverse = kolorist(7, 27); 134 | export const hidden = kolorist(8, 28); 135 | export const strikethrough = kolorist(9, 29); 136 | 137 | // colors 138 | export const black = kolorist(30, 39); 139 | export const red = kolorist(31, 39); 140 | export const green = kolorist(32, 39); 141 | export const yellow = kolorist(33, 39); 142 | export const blue = kolorist(34, 39); 143 | export const magenta = kolorist(35, 39); 144 | export const cyan = kolorist(36, 39); 145 | export const white = kolorist(97, 39); 146 | export const gray = kolorist(90, 39); 147 | 148 | export const lightGray = kolorist(37, 39); 149 | export const lightRed = kolorist(91, 39); 150 | export const lightGreen = kolorist(92, 39); 151 | export const lightYellow = kolorist(93, 39); 152 | export const lightBlue = kolorist(94, 39); 153 | export const lightMagenta = kolorist(95, 39); 154 | export const lightCyan = kolorist(96, 39); 155 | 156 | // background colors 157 | export const bgBlack = kolorist(40, 49); 158 | export const bgRed = kolorist(41, 49); 159 | export const bgGreen = kolorist(42, 49); 160 | export const bgYellow = kolorist(43, 49); 161 | export const bgBlue = kolorist(44, 49); 162 | export const bgMagenta = kolorist(45, 49); 163 | export const bgCyan = kolorist(46, 49); 164 | export const bgWhite = kolorist(107, 49); 165 | export const bgGray = kolorist(100, 49); 166 | 167 | export const bgLightRed = kolorist(101, 49); 168 | export const bgLightGreen = kolorist(102, 49); 169 | export const bgLightYellow = kolorist(103, 49); 170 | export const bgLightBlue = kolorist(104, 49); 171 | export const bgLightMagenta = kolorist(105, 49); 172 | export const bgLightCyan = kolorist(106, 49); 173 | export const bgLightGray = kolorist(47, 49); 174 | 175 | // 256 support 176 | export const ansi256 = (n: number) => 177 | kolorist('38;5;' + n, 0, SupportLevel.ansi256); 178 | export const ansi256Bg = (n: number) => 179 | kolorist('48;5;' + n, 0, SupportLevel.ansi256); 180 | 181 | // TrueColor 24bit support 182 | export const trueColor = (r: number, g: number, b: number) => { 183 | return options.supportLevel === SupportLevel.ansi256 184 | ? ansi256(rgbToAnsi256(r, g, b)) 185 | : kolorist(`38;2;${r};${g};${b}`, 0, SupportLevel.trueColor); 186 | }; 187 | export const trueColorBg = (r: number, g: number, b: number) => { 188 | return options.supportLevel === SupportLevel.ansi256 189 | ? ansi256Bg(rgbToAnsi256(r, g, b)) 190 | : kolorist(`48;2;${r};${g};${b}`, 0, SupportLevel.trueColor); 191 | }; 192 | 193 | // Links 194 | const OSC = '\u001B]'; 195 | const BEL = '\u0007'; 196 | const SEP = ';'; 197 | 198 | export function link(text: string, url: string) { 199 | return options.enabled 200 | ? OSC + '8' + SEP + SEP + url + BEL + text + OSC + '8' + SEP + SEP + BEL 201 | : `${text} (\u200B${url}\u200B)`; 202 | } 203 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import * as k from './index'; 2 | import { strict as t } from 'assert'; 3 | import * as pty from 'node-pty'; 4 | import * as child_process from 'child_process'; 5 | 6 | function columnize(arr: string[], count: number = 16): string { 7 | let out = ''; 8 | for (let i = 0; i < arr.length; i++) { 9 | out += arr[i]; 10 | if ((i + 1) % count === 0) { 11 | out += '\n'; 12 | } 13 | } 14 | 15 | return out; 16 | } 17 | 18 | describe('colors', () => { 19 | beforeEach(() => { 20 | k.options.enabled = true; // Always enable colors, even in CLI environments 21 | k.options.supportLevel = k.SupportLevel.ansi256; 22 | }); 23 | 24 | it('should print colors', () => { 25 | t.equal(k.cyan('foo'), '\u001b[36mfoo\u001b[39m'); 26 | }); 27 | 28 | it('should nest colors', () => { 29 | t.equal( 30 | k.green(`foo ${k.lightCyan('bar')} bob`), 31 | '\u001b[32mfoo \u001b[96mbar\u001b[32m bob\u001b[39m' 32 | ); 33 | }); 34 | 35 | it('should nest background colors', () => { 36 | t.equal( 37 | k.bgYellow(`foo ${k.bgGray('bar')} bob`), 38 | '\u001b[43mfoo \u001b[100mbar\u001b[43m bob\u001b[49m' 39 | ); 40 | }); 41 | 42 | it('should print demo', () => { 43 | const strs = Object.keys(k) 44 | .filter( 45 | key => 46 | ![ 47 | 'options', 48 | 'ansi256', 49 | 'ansi256Bg', 50 | 'link', 51 | 'SupportLevel', 52 | 'trueColor', 53 | 'trueColorBg', 54 | ].includes(key) 55 | ) 56 | .map(x => (k as any)[x]('foobar')); 57 | 58 | console.log(columnize(strs, 16)); 59 | }); 60 | 61 | describe('ansi256', () => { 62 | it('should print foreground demo', () => { 63 | const strs = new Array(256).fill(0).map((_, i) => k.ansi256(i)('foo')); 64 | console.log(columnize(strs, 16)); 65 | }); 66 | 67 | it('should print background demo', () => { 68 | const strs = new Array(256).fill(0).map((_, i) => k.ansi256Bg(i)('foo')); 69 | console.log(columnize(strs, 16)); 70 | }); 71 | 72 | it('should mix with modifiers', () => { 73 | const strs = new Array(256) 74 | .fill(0) 75 | .map((_, i) => k.dim(k.ansi256(i)('foo'))); 76 | console.log(columnize(strs, 16)); 77 | }); 78 | 79 | it('should be stripped', () => { 80 | t.equal(k.stripColors(k.ansi256(194)('foo')), 'foo'); 81 | }); 82 | 83 | it('should be ignored if no terminal support', () => { 84 | k.options.supportLevel = k.SupportLevel.ansi; 85 | t.equal(JSON.stringify(k.ansi256(194)('foo')), JSON.stringify('foo')); 86 | }); 87 | }); 88 | 89 | describe('TrueColor 24bit', () => { 90 | beforeEach(() => { 91 | k.options.supportLevel = k.SupportLevel.trueColor; 92 | }); 93 | 94 | it('should print foreground', () => { 95 | const str = k.trueColor(134, 239, 172)('foo'); 96 | console.log(str); 97 | }); 98 | 99 | it('should print background', () => { 100 | const str = k.trueColorBg(134, 239, 172)('foo'); 101 | console.log(str); 102 | }); 103 | 104 | it('should mix with modifiers', () => { 105 | console.log(k.dim(k.trueColor(134, 239, 172)('foo'))); 106 | console.log(k.dim(k.trueColorBg(134, 239, 172)(k.black('foo')))); 107 | }); 108 | 109 | it('should be stripped', () => { 110 | t.equal(k.stripColors(k.trueColor(134, 239, 172)('foo')), 'foo'); 111 | }); 112 | 113 | it('should be ignored if no terminal support', () => { 114 | k.options.supportLevel = k.SupportLevel.ansi; 115 | t.equal( 116 | JSON.stringify(k.trueColor(134, 239, 172)('foo')), 117 | JSON.stringify('foo') 118 | ); 119 | }); 120 | 121 | it('should convert color space to ansi256 if possible', () => { 122 | k.options.supportLevel = k.SupportLevel.ansi256; 123 | t.equal(k.trueColor(134, 239, 172)('foo'), k.ansi256(157)('foo')); 124 | t.equal(k.trueColorBg(134, 239, 172)('foo'), k.ansi256Bg(157)('foo')); 125 | }); 126 | }); 127 | 128 | it('should toggle enabled or disabled', () => { 129 | k.options.enabled = true; 130 | t.equal(k.cyan('foo'), '\u001b[36mfoo\u001b[39m'); 131 | 132 | k.options.enabled = false; 133 | t.equal(k.cyan('foo'), 'foo'); 134 | 135 | k.options.enabled = true; 136 | t.equal(k.cyan('foo'), '\u001b[36mfoo\u001b[39m'); 137 | }); 138 | }); 139 | 140 | describe('color switch', () => { 141 | it('should be enabled in terminals by default', done => { 142 | let output = ''; 143 | const term = pty.spawn( 144 | process.execPath, 145 | [ 146 | '-r', 147 | '@esbuild-kit/cjs-loader', 148 | '-e', 149 | 'console.log(require("./index.ts").blue("foo"))', 150 | ], 151 | { 152 | name: 'test with pseudo tty', 153 | cols: 80, 154 | rows: 30, 155 | cwd: __dirname, 156 | env: {}, 157 | } 158 | ); 159 | term.onData(data => (output += data)); 160 | term.onExit(() => { 161 | t.equal( 162 | JSON.stringify(output.trim()), 163 | JSON.stringify('\x1B[34mfoo\x1B[39m') 164 | ); 165 | done(); 166 | }); 167 | }).timeout(20000); // typescript is slow 168 | 169 | it('should be disabled in non-interactive terminals', done => { 170 | let output = ''; 171 | const subprocess = child_process.spawn( 172 | process.execPath, 173 | [ 174 | '-r', 175 | '@esbuild-kit/cjs-loader', 176 | '-e', 177 | 'console.log(require("./index.ts").blue("foo"))', 178 | ], 179 | { 180 | cwd: __dirname, 181 | stdio: 'pipe', 182 | env: {}, 183 | } 184 | ); 185 | subprocess.stdout.on('data', data => (output += data)); 186 | subprocess.stderr.on('data', data => (output += data)); 187 | subprocess.on('exit', () => { 188 | t.equal(JSON.stringify(output.trim()), JSON.stringify('foo')); 189 | done(); 190 | }); 191 | }).timeout(20000); // typescript is slow 192 | 193 | it('should be disabled when TERM=dumb', done => { 194 | let output = ''; 195 | const subprocess = child_process.spawn( 196 | process.execPath, 197 | [ 198 | '-r', 199 | '@esbuild-kit/cjs-loader', 200 | '-e', 201 | 'console.log(require("./index.ts").blue("foo"))', 202 | ], 203 | { 204 | cwd: __dirname, 205 | env: { 206 | TERM: 'dumb', 207 | }, 208 | stdio: 'pipe', 209 | } 210 | ); 211 | subprocess.stdout.on('data', data => (output += data)); 212 | subprocess.stderr.on('data', data => (output += data)); 213 | subprocess.on('exit', () => { 214 | t.equal(JSON.stringify(output.trim()), JSON.stringify('foo')); 215 | done(); 216 | }); 217 | }).timeout(20000); // typescript is slow 218 | 219 | it('should be enabled in CI environments', done => { 220 | let output = ''; 221 | const subprocess = child_process.spawn( 222 | process.execPath, 223 | [ 224 | '-r', 225 | '@esbuild-kit/cjs-loader', 226 | '-e', 227 | 'console.log(require("./index.ts").blue("foo"))', 228 | ], 229 | { 230 | cwd: __dirname, 231 | env: { 232 | CI: 'true', 233 | GITLAB_CI: 'true', 234 | }, 235 | stdio: 'pipe', 236 | } 237 | ); 238 | subprocess.stdout.on('data', data => (output += data)); 239 | subprocess.stderr.on('data', data => (output += data)); 240 | subprocess.on('exit', () => { 241 | t.equal(JSON.stringify(output.trim()), JSON.stringify(k.blue('foo'))); 242 | done(); 243 | }); 244 | }).timeout(20000); // typescript is slow 245 | }); 246 | 247 | describe('strip colors', () => { 248 | it('should remove colors from string', () => { 249 | t.equal(k.stripColors(k.red('foo')), 'foo'); 250 | }); 251 | 252 | it('should strip link', () => { 253 | t.equal(k.stripColors(k.link('foo', 'foo')), 'foo'); 254 | }); 255 | }); 256 | 257 | describe('links', () => { 258 | it('should render links', () => { 259 | t.equal( 260 | k.link('my link', 'https://example.com'), 261 | '\u001b]8;;https://example.com\u0007my link\u001b]8;;\u0007' 262 | ); 263 | 264 | k.options.enabled = false; 265 | t.equal( 266 | k.link('my link', 'https://example.com'), 267 | 'my link (\u200Bhttps://example.com\u200B)' 268 | ); 269 | k.options.enabled = true; 270 | }); 271 | }); 272 | --------------------------------------------------------------------------------