Skip to content

fix: respect FORCE_COLOR level by capping detected terminal capability#165

Closed
guoyangzhen wants to merge 1 commit intochalk:mainfrom
guoyangzhen:fix/force-color-cap
Closed

fix: respect FORCE_COLOR level by capping detected terminal capability#165
guoyangzhen wants to merge 1 commit intochalk:mainfrom
guoyangzhen:fix/force-color-cap

Conversation

@guoyangzhen
Copy link
Copy Markdown

Summary

Fixes #131

When FORCE_COLOR is explicitly set (e.g., FORCE_COLOR=1), the returned color level should be capped at the specified value. Previously, terminal detection would override FORCE_COLOR, making it impossible to reduce color support.

Problem

FORCE_COLOR=1 node -e "console.log(require('chalk').supportsColor)"
# Expected: { level: 1, hasBasic: true, has256: false, has16m: false }
# Actual (in Alacritty/iTerm/etc): { level: 3, hasBasic: true, has256: true, has16m: true }

The issue: forceColor was used as min (floor) but not as cap (ceiling). Terminal capability detection (COLORTERM=truecolor, TERM checks, etc.) would return higher levels without respecting the forced value.

Fix

Add a cap variable set to forceColor when explicitly provided, otherwise Infinity. Apply Math.min(detected_level, cap) at all early return points, ensuring the forced level is never exceeded while still allowing lower detected levels to pass through.

Behavior after fix

  • FORCE_COLOR=0 → level 0 (no color)
  • FORCE_COLOR=1 → level 1 max (basic 16 colors)
  • FORCE_COLOR=2 → level 2 max (256 colors)
  • FORCE_COLOR=3 → level 3 (truecolor, same as before)
  • No FORCE_COLOR → detected level (same as before)

When FORCE_COLOR is explicitly set (e.g., FORCE_COLOR=1), the returned
color level should be capped at the specified value. Previously, terminal
detection would override FORCE_COLOR, making it impossible to reduce
color support.

Fixes chalk#131
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"Can't resolve node:tty" when using nextjs and yarn 3

1 participant