diff --git a/pkg/src/message.js b/pkg/src/message.js index e0eb81b..b819495 100644 --- a/pkg/src/message.js +++ b/pkg/src/message.js @@ -1,15 +1,29 @@ -import c from 'picocolors' +import picocolors from 'picocolors' import { formatMessagePath as fp, getPkgPathValue, replaceLast } from './utils.js' +/** @type { import('picocolors/types.js').Colors | undefined } */ +let _picocolorsHasColors +/** @type { import('picocolors/types.js').Colors | undefined } */ +let _picocolorsNoColors + /** * @param {import('../index.d.ts').Message} m * @param {import('./utils.js').Pkg} pkg + * @param {import('../utils.d.ts').FormatMessageOptions} opts */ -export function formatMessage(m, pkg) { +export function formatMessage(m, pkg, opts = {}) { + /** @type { import('picocolors/types.js').Colors } */ + let c = picocolors + if (opts.color === true) { + c = _picocolorsHasColors ??= picocolors.createColors(true) + } else if (opts.color === false) { + c = _picocolorsNoColors ??= picocolors.createColors(false) + } + /** @param {string[]} path */ const pv = (path) => getPkgPathValue(pkg, path) diff --git a/pkg/utils.d.ts b/pkg/utils.d.ts index bba4feb..6b1245c 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 FormatMessageOptions { + /** + * Whether the returned string should contain color. + * - `true`: Force has color. + * - `false`: Force no color. + * - `undefined`: Default to whether the environment supports color. + */ + 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, + opts?: FormatMessageOptions ): string | undefined