index.cjs 2.3 KB

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