diff --git a/src/js/node/util.js b/src/js/node/util.js index e8adc966c8c53..548b663f8d10d 100644 --- a/src/js/node/util.js +++ b/src/js/node/util.js @@ -240,6 +240,23 @@ var toUSVString = input => { return (input + "").toWellFormed(); }; +function styleText(format, text) { + if (typeof text !== "string") { + const e = new Error(`The text argument must be of type string. Received type ${typeof text}`); + e.code = "ERR_INVALID_ARG_TYPE"; + throw e; + } + const formatCodes = inspect.colors[format]; + if (formatCodes == null) { + const e = new Error( + `The value "${typeof format === "symbol" ? format.description : format}" is invalid for argument 'format'. Reason: must be one of: ${Object.keys(inspect.colors).join(", ")}`, + ); + e.code = "ERR_INVALID_ARG_VALUE"; + throw e; + } + return `\u001b[${formatCodes[0]}m${text}\u001b[${formatCodes[1]}m`; +} + export default Object.assign(cjs_exports, { format, formatWithOptions, @@ -273,4 +290,5 @@ export default Object.assign(cjs_exports, { TextDecoder, TextEncoder, parseArgs, + styleText, }); diff --git a/test/js/node/util/util.test.js b/test/js/node/util/util.test.js index df995955a2cce..4c1c51511e08c 100644 --- a/test/js/node/util/util.test.js +++ b/test/js/node/util/util.test.js @@ -325,4 +325,36 @@ describe("util", () => { "wow({ obj: \u001B[33mtrue\u001B[39m })", ); }); + + it("styleText", () => { + [undefined, null, false, 5n, 5, Symbol(), () => {}, {}, []].forEach(invalidOption => { + assert.throws( + () => { + util.styleText(invalidOption, "test"); + }, + { + code: "ERR_INVALID_ARG_VALUE", + }, + ); + assert.throws( + () => { + util.styleText("red", invalidOption); + }, + { + code: "ERR_INVALID_ARG_TYPE", + }, + ); + }); + + assert.throws( + () => { + util.styleText("invalid", "text"); + }, + { + code: "ERR_INVALID_ARG_VALUE", + }, + ); + + assert.strictEqual(util.styleText("red", "test"), "\u001b[31mtest\u001b[39m"); + }); });