7.10.94 • Published 12 months ago

@patrtorg/unde-eos v7.10.94

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

@patrtorg/unde-eos

npm

A JavaScript ANSI color/style management. ANSI parsing. ANSI to CSS. Small, clean, no dependencies.

npm install @patrtorg/unde-eos

What For

Why Another One?

Other tools lack consistency, failing to solve a simple hierarchy problem:

require ('colors') // a popular color utility

console.log (('foo'.cyan + 'bar').red)

pic

WTF?! The bar word above should be rendered in red, but it's not! That sucks. It's because ANSI codes are linear, not hierarchical (as with XML/HTML). A special kind of magic is needed to make this work. Ansicolor does that magic for you:

require ('@patrtorg/unde-eos').nice // .nice for unsafe String extensions

console.log (('foo'.cyan + 'bar').red)

pic

Nice!

Crash Course

Importing (as methods):

import { green, inverse, bgLightCyan, underline, dim } from '@patrtorg/unde-eos'
const { green, inverse, bgLightCyan, underline, dim } = require ('@patrtorg/unde-eos')

Usage:

console.log ('foo' + green (inverse (bgLightCyan ('bar')) + 'baz') + 'qux')
console.log (underline.bright.green ('foo' + dim.red.bgLightCyan ('bar'))) // method chaining

Importing (as object):

import { @patrtorg/unde-eos, ParsedSpan } from '@patrtorg/unde-eos' // along with type definitions
import @patrtorg/unde-eos from '@patrtorg/unde-eos'

Nice Mode (not recommended)

const ansi = require ('@patrtorg/unde-eos').nice

The ('@patrtorg/unde-eos').nice export defines styling APIs on the String prototype directly. It uses an ad-hoc DSL (sort of) for infix-style string coloring. The nice is convenient, but not safe, avoid using it in public modules, as it alters global objects, and that might cause potential hard-to-debug compatibility issues.

console.log ('foo'.red.bright + 'bar'.bgYellow.underline.dim)

Supported Styles

'foreground colors'
    .red.green.yellow.blue.magenta.cyan.white.darkGray.black
'light foreground colors'
    .lightRed.lightGreen.lightYellow.lightBlue.lightMagenta.lightCyan.lightGray
'background colors'
    .bgRed.bgGreen.bgYellow.bgBlue.bgMagenta.bgCyan.bgWhite.bgDarkGray.bgBlack
'light background colors'
    .bgLightRed.bgLightGreen.bgLightYellow.bgLightBlue.bgLightMagenta.bgLightCyan.bgLightGray
'styles'
    .bright.dim.italic.underline.inverse // your platform should support italic

You also can obtain all those style names (for reflection purposes):

const { names } = require ('@patrtorg/unde-eos')

names // ['red', 'green', ...

Removing ANSI Styles From Strings

const { strip } = require ('@patrtorg/unde-eos')

strip ('\u001b[0m\u001b[4m\u001b[42m\u001b[31mfoo\u001b[39m\u001b[49m\u001b[24mfoo\u001b[0m')) // 'foofoo'

Checking If Strings Contain ANSI Codes

const { isEscaped, green } = require ('@patrtorg/unde-eos')

isEscaped ('text')         // false
isEscaped (green ('text')) // true

Converting to CSS/HTML

Inspection of ANSI styles in arbitrary strings is essential when implementing platform-agnostic logging — that piece of code is available under command line interface and in a browser as well. Here's an example of how you would parse a colored string into an array-like structure. That structure can be traversed later to build HTML/JSON/XML or any other markup/syntax.

const { parse } = require ('@patrtorg/unde-eos')

const parsed = parse ('foo'.bgLightRed.bright.italic + 'bar'.red.dim)

The ansi.parse () method will return a pseudo-array of styled spans, you can iterate over it with a for ... of loop and convert it to an array with the spread operator (...). Also, there's the .spans property for obtaining the already-spread array directly:

assert.deepEqual (parsed.spans /* or [...parsed] */,

    [ { css: 'font-weight: bold;font-style: italic;background:rgba(255,51,0,1);',
        italic: true,
        bold: true,
        color: { bright: true },
        bgColor: { name: 'lightRed' },
        text: 'foo' },

      { css: 'color:rgba(204,0,0,0.5);',
        color: { name: 'red', dim: true },
        text: 'bar' } ])

Custom Color Themes

You can change default RGB values (won't work in terminals, affects only the ANSI→CSS transformation part):

const ansi = require ('@patrtorg/unde-eos')

ansi.rgb = {

    black:        [0,     0,   0],    
    darkGray:     [100, 100, 100],
    lightGray:    [200, 200, 200],
    white:        [255, 255, 255],

    red:          [204,   0,   0],
    lightRed:     [255,  51,   0],
    
    green:        [0,   204,   0],
    lightGreen:   [51,  204,  51],
    
    yellow:       [204, 102,   0],
    lightYellow:  [255, 153,  51],
    
    blue:         [0,     0, 255],
    lightBlue:    [26,  140, 255],
    
    magenta:      [204,   0, 204],
    lightMagenta: [255,   0, 255],
    
    cyan:         [0,   153, 255],
    lightCyan:    [0,   204, 255],
}

Chrome DevTools Compatibility

Web browsers usually implement their own proprietary CSS-based color formats for console.log and most of them fail to display standard ANSI colors. Ansicolor offers you a helper method to convert ANSI-styled strings to browser-compatible argument lists acceptable by Chrome's console.log:

const { bgGreen, red, parse } = require ('@patrtorg/unde-eos')

const string = 'foo' + bgGreen (red.underline.bright.inverse ('bar') + 'baz')
const parsed = parse (string)

console.log (...parsed.asChromeConsoleLogArguments) // prints with colors in Chrome!

Here's what the format looks like:

parsed.asChromeConsoleLogArguments // [ "%cfoo%cbar%cbaz",
                                   //   "",
                                   //   "font-weight: bold;text-decoration: underline;background:rgba(255,51,0,1);color:rgba(0,204,0,1);",
                                   //   "background:rgba(0,204,0,1);"
                                   // ]

Play with this feature online: demo page. Open the DevTools console and type expressions in the input box to see colored console output.

Happy logging!

Projects That Use @patrtorg/unde-eos

  • Ololog! — a better console.log for the log-driven debugging junkies
  • CCXT — a cryptocurrency trading API with 130+ exchanges
  • Grafana — beautiful monitoring & metric analytics & dashboards
metadatatoArrayfunctionwafArray.prototype.containselasticacheschemacollection.es6functionsrangeerrorURLassignquotekeyestreenopeenvironmentsfigletperformanceURLSearchParamsbabelreal-timechaiproxybinaryargveslinteventEmittermacosstringRFC-6455rulesutil.inspectremovefastpropertiesqsinferenceloadingmake diriamcallbackreducersettingsdataView__proto__speedbindhotauthenticationcryptregexincludesbyteOffsetArray.prototype.findLastIndexsigtermvariablesfsless compilerieoperating-systemreact-testing-libraryless.jsfront-endletastArrayBufferfetchserviceiterationvalidSystem.global@@toStringTaglrumomentfantasy-landfunction.lengthshebangauthbytepropertyebsprocessObjectObject.valuesStreamshasOwnPropertykoreanefficientsesWeakSetlogbrowserslistIteratorrequestentriesglobal this valueexit-codecallboundpipeprogresstesterclassnamesmobileArray.prototype.flatMapunicodesymbolsnativeInt32Arrayio-tsnodepredictablesymlinksprettyjsxhandlerPromiseinstallpoint-freecircularsubprocessbootstrap lesstrimRightansiownbrowserECMAScript 7global objectmkdirbundlerawspurepositivetypedjson-schemawgetfnmatchrdsa11ystylesgetcss lessECMAScript 2020dependency managerString.prototype.trimdefinePropertySymbol.toStringTagjsonschemaserialization6to5ES6fast-deep-copylesscsscjkreplayasciiUint8ClampedArrayenvironmentenvchannelpolyfilldiffprefixtypeofAsyncIteratorvpclibphonenumberES3callbindgroupencryptionexpressionstyled-componentsasyncglobalThismockingtraverseform-validationlocationonceassertsECMAScript 2016npmignoreapiequalcompareconfigruntimerandomES2019graphqlobjstoragegatewayrapidbusyfast-copyexecObject.assigneslint-pluginStyleSheetcoloursideRxJSWebSocketjoiimportreact-hookscommandexitstreamscheckforkpnpm9fullwidthReactiveExtensionsprunegetOwnPropertyDescriptorclass-validatorUint32ArrayespreesharedparsebddES2022signalvalidatereactinlivehelpersECMAScript 5ES2020inspecttextdom-testing-librarylockfileparserbinpreserve-symlinkswritetslibes8varsinternalbinariescore-jses2016shimweakmapcolumnstatelessslotextendstylecsstransporttrimEndexecuteirqcloudsearchemramazontyped arraypackage.jsonvalidatordescriptorindicatorvarinstallerYAMLajaxconsolefluxformatwhichjsnamescall-boundpluginclientObject.entrieshasposeoutputspawndatecertificatesairbnblintacornhelperlengthbyteLengthformgenericsuploadESnextchromiumconfigurableweaksetutilsprotobufES8utilitiestypescriptmonorepoprototypedescriptiontrimLefti18nerror-handlingomitformattingTypedArrayCSSStyleDeclarationqueuethreestyleguideworkerfast-deep-clonevaluesassertECMAScript 20153deast-asian-widthECMAScript 2023codesSymboljshintarraybuffertypedarrayfindLastECMAScript 2017terminalstreamfindHyBiObject.isES2016fastifytakecss-in-jssortedtrimtypanioneffect-tsArrayBuffer.prototype.slicelistenersroute53maketypesafeiteratorjson-schema-validationglobalreact animationvariables in cssObservablecommanderObject.defineProperty.envdeep-clonees-shim APIcorereduceclassnameexpress
7.10.94

12 months ago

7.10.93

12 months ago

7.10.92

12 months ago

7.10.91

1 year ago

7.10.90

1 year ago

7.10.89

1 year ago

7.10.88

1 year ago

7.10.87

1 year ago

7.10.86

1 year ago

7.10.85

1 year ago

7.10.84

1 year ago

6.10.84

1 year ago

6.10.83

1 year ago

6.9.83

1 year ago

6.9.82

1 year ago

6.9.81

1 year ago

6.9.80

1 year ago

6.9.79

1 year ago

6.9.78

1 year ago

6.9.77

1 year ago

6.9.76

1 year ago

6.9.75

1 year ago

6.9.74

1 year ago

6.9.73

1 year ago

6.9.72

1 year ago

6.9.71

1 year ago

6.9.70

1 year ago

6.9.69

1 year ago

6.9.68

1 year ago

6.9.67

1 year ago

6.9.66

1 year ago

6.9.65

1 year ago

6.9.64

1 year ago

6.9.63

1 year ago

6.9.62

1 year ago

6.9.61

1 year ago

6.9.60

1 year ago

6.8.60

1 year ago

6.8.59

1 year ago

6.8.58

1 year ago

6.8.57

1 year ago

6.8.56

1 year ago

6.8.55

1 year ago

6.8.54

1 year ago

6.8.53

1 year ago

5.8.53

1 year ago

5.7.53

1 year ago

5.7.52

1 year ago

5.6.52

1 year ago

5.6.51

1 year ago

5.6.50

1 year ago

5.6.49

1 year ago

5.6.48

1 year ago

5.6.47

1 year ago

5.5.47

1 year ago

5.5.46

1 year ago

5.5.45

1 year ago

5.5.44

1 year ago

5.5.43

1 year ago

5.5.42

1 year ago

5.5.41

1 year ago

4.5.41

1 year ago

4.5.40

1 year ago

4.5.39

1 year ago

4.5.38

1 year ago

4.5.37

1 year ago

4.5.36

1 year ago

4.5.35

1 year ago

4.5.34

1 year ago

3.5.34

1 year ago

3.5.33

1 year ago

3.5.32

1 year ago

3.5.31

1 year ago

3.5.30

1 year ago

3.4.30

1 year ago

3.4.29

1 year ago

3.4.28

1 year ago

3.4.27

1 year ago

3.4.26

1 year ago

3.4.25

1 year ago

3.4.24

1 year ago

3.4.23

1 year ago

3.4.22

1 year ago

3.4.21

1 year ago

2.4.21

1 year ago

2.4.20

1 year ago

2.4.19

1 year ago

2.4.18

1 year ago

2.4.17

1 year ago

2.4.16

1 year ago

2.4.15

1 year ago

2.4.14

1 year ago

2.4.13

1 year ago

2.4.12

1 year ago

1.4.12

1 year ago

1.4.11

1 year ago

1.4.10

1 year ago

1.4.9

1 year ago

1.4.8

1 year ago

1.4.7

1 year ago

1.4.6

1 year ago

1.4.5

1 year ago

1.3.5

1 year ago

1.2.5

1 year ago

1.2.4

1 year ago

1.1.4

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

1.1.1

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago