picocolors.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. let tty = require("tty")
  2. let isColorSupported =
  3. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  4. ("FORCE_COLOR" in process.env ||
  5. process.argv.includes("--color") ||
  6. process.platform === "win32" ||
  7. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  8. "CI" in process.env)
  9. let formatter =
  10. (open, close, replace = open) =>
  11. input => {
  12. let string = "" + input
  13. let index = string.indexOf(close, open.length)
  14. return ~index
  15. ? open + replaceClose(string, close, replace, index) + close
  16. : open + string + close
  17. }
  18. let replaceClose = (string, close, replace, index) => {
  19. let start = string.substring(0, index) + replace
  20. let end = string.substring(index + close.length)
  21. let nextIndex = end.indexOf(close)
  22. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  23. }
  24. let createColors = (enabled = isColorSupported) => ({
  25. isColorSupported: enabled,
  26. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  27. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  28. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  29. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  30. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  31. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  32. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  33. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  34. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  35. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  36. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  37. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  38. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  39. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  40. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  41. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  42. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  43. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  44. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  45. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  46. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  47. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  48. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  49. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  50. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  51. })
  52. module.exports = createColors()
  53. module.exports.createColors = createColors