util: styleText restores overridden color after nested style when format is an array
Version
v26.13.0
Platform
Microsoft Windows NT 10.0.19045.0 x64
Subsystem
util
What steps will reproduce the bug?
node -p "util.styleText(['red', 'green'], 'a' + util.styleText('blue', 'b') + 'a')"
How often does it reproduce? Is there a required condition?
always
What is the expected behavior? Why is that the expected behavior?
Both 'a' characters (before and after the nested blue 'b') should be colored green (\u001b[32m).
This works correctly in chalk:
import chalk from 'chalk';
console.log(chalk.red.green('a' + chalk.blue('b') + 'a'));
What do you see instead?
The first a is green (\u001b[32m), b is blue (\u001b[34m), and the second a is red (\u001b[31m):
Additional information
May be related https://github.com/nodejs/node/pull/59098
Reproduced on Linux with v22.20.0, v24.22.3, v25.6.1 and main. With validateStream: false on both calls, so colours are emitted outside a TTY:
util.styleText(['red', 'green'], 'a' + util.styleText('blue', 'b', { validateStream: false }) + 'a', { validateStream: false })
returns \e[31m\e[32ma\e[34mb\e[31ma\e[39m\e[39m, so the second a is red.
Restoring the outer colour after a nested style was added in #59098 (v24.5.0, v22.19.0). On v20.20.2 the second a falls back to the default colour (...\e[34mb\e[39ma...), so this isn't a regression, but the restore picks the wrong colour.
Cause: styleText() applies the formats in order, and each one replaces the nested close code with its own open code (replaceCloseCode() in lib/util.js). red runs first and turns \e[39m into \e[31m, so by the time green runs there is no \e[39m left to replace.
I tried walking the formats from last to first in a local build of main (building openCodes and closeCodes in the same order as before): the second a becomes green, ['bold', 'red'] around a nested green still restores red, the same case with hex colours works, and test-util-styletext* passes.