From 014c2cd6751cbe37ad502b90ed05c27522372698 Mon Sep 17 00:00:00 2001 From: zanminkian Date: Sun, 15 Sep 2024 15:49:25 +0000 Subject: [PATCH] feat: support `color` options --- pkg/src/message.js | 16 ++++++++++++++-- pkg/utils.d.ts | 13 ++++++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/pkg/src/message.js b/pkg/src/message.js index e0eb81b..ef65df5 100644 --- a/pkg/src/message.js +++ b/pkg/src/message.js @@ -1,15 +1,27 @@ -import c from 'picocolors' +import picocolors from 'picocolors' import { formatMessagePath as fp, getPkgPathValue, replaceLast } from './utils.js' +const picoHasColors = picocolors.createColors(true) +const picoNoColors = picocolors.createColors(false) + /** * @param {import('../index.d.ts').Message} m * @param {import('./utils.js').Pkg} pkg + * @param {import('../utils.d.ts').FormatMessageOpt} opt */ -export function formatMessage(m, pkg) { +export function formatMessage(m, pkg, opt = {}) { + /** @type { import("picocolors/types.js").Colors } */ + let c = picocolors + if (opt.color === true) { + c = picoHasColors + } else if (opt.color === false) { + c = picoNoColors + } + /** @param {string[]} path */ const pv = (path) => getPkgPathValue(pkg, path) diff --git a/pkg/utils.d.ts b/pkg/utils.d.ts index bba4feb..79973d9 100644 --- a/pkg/utils.d.ts +++ b/pkg/utils.d.ts @@ -2,9 +2,20 @@ import type { Message } from './index.js' type Pkg = Record +export interface FormatMessageOpt { + /** + * Used to determine if the returned string contains color. + * - true: Force has color. + * - false: Force no color. + * - undefined: Default to whether the environment supports color (already handled by picocolors by default). + */ + color?: boolean | undefined +} + export declare function formatMessagePath(path: string[]): string export declare function getPkgPathValue(pkg: Pkg, path: string[]): any export declare function formatMessage( msg: Message, - pkg: Pkg + pkg: Pkg, + opt?: FormatMessageOpt ): string | undefined