index.cjs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const tty = require("tty")
  2. const env = process.env
  3. const isDisabled = "NO_COLOR" in env
  4. const isForced = "FORCE_COLOR" in env
  5. const isWindows = process.platform === "win32"
  6. const isCompatibleTerminal =
  7. tty && tty.isatty(1) && env.TERM && env.TERM !== "dumb"
  8. const isCI =
  9. "CI" in env &&
  10. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env)
  11. let enabled =
  12. !isDisabled && (isForced || isWindows || isCompatibleTerminal || isCI)
  13. const raw = (open, close, searchRegex, replaceValue) => (s) =>
  14. enabled
  15. ? open +
  16. (~(s += "").indexOf(close, 4) // skip opening \x1b[
  17. ? s.replace(searchRegex, replaceValue)
  18. : s) +
  19. close
  20. : s
  21. const init = (open, close) => {
  22. return raw(
  23. `\x1b[${open}m`,
  24. `\x1b[${close}m`,
  25. new RegExp(`\\x1b\\[${close}m`, "g"),
  26. `\x1b[${open}m`
  27. )
  28. }
  29. exports.options = Object.defineProperty({}, "enabled", {
  30. get: () => enabled,
  31. set: (value) => (enabled = value),
  32. })
  33. exports.reset = init(0, 0)
  34. exports.bold = raw("\x1b[1m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[1m")
  35. exports.dim = raw("\x1b[2m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[2m")
  36. exports.italic = init(3, 23)
  37. exports.underline = init(4, 24)
  38. exports.inverse = init(7, 27)
  39. exports.hidden = init(8, 28)
  40. exports.strikethrough = init(9, 29)
  41. exports.black = init(30, 39)
  42. exports.red = init(31, 39)
  43. exports.green = init(32, 39)
  44. exports.yellow = init(33, 39)
  45. exports.blue = init(34, 39)
  46. exports.magenta = init(35, 39)
  47. exports.cyan = init(36, 39)
  48. exports.white = init(37, 39)
  49. exports.gray = init(90, 39)
  50. exports.bgBlack = init(40, 49)
  51. exports.bgRed = init(41, 49)
  52. exports.bgGreen = init(42, 49)
  53. exports.bgYellow = init(43, 49)
  54. exports.bgBlue = init(44, 49)
  55. exports.bgMagenta = init(45, 49)
  56. exports.bgCyan = init(46, 49)
  57. exports.bgWhite = init(47, 49)
  58. exports.blackBright = init(90, 39)
  59. exports.redBright = init(91, 39)
  60. exports.greenBright = init(92, 39)
  61. exports.yellowBright = init(93, 39)
  62. exports.blueBright = init(94, 39)
  63. exports.magentaBright = init(95, 39)
  64. exports.cyanBright = init(96, 39)
  65. exports.whiteBright = init(97, 39)
  66. exports.bgBlackBright = init(100, 49)
  67. exports.bgRedBright = init(101, 49)
  68. exports.bgGreenBright = init(102, 49)
  69. exports.bgYellowBright = init(103, 49)
  70. exports.bgBlueBright = init(104, 49)
  71. exports.bgMagentaBright = init(105, 49)
  72. exports.bgCyanBright = init(106, 49)
  73. exports.bgWhiteBright = init(107, 49)