perf: cache ANSI prefix regex in truncate instead of re-creating per call

This commit is contained in:
2026-05-03 21:14:07 -04:00
parent 4e36542b8b
commit c8c5de590d

View File

@@ -2,6 +2,7 @@ import type { ModuleSpec, RenderedModule } from "./types";
// eslint-disable-next-line no-control-regex
const ANSI_RE = new RegExp("\\u001b\\[[0-9;]*m", "g");
const ANSI_PREFIX_RE = /^\u001b\[[0-9;]*m/;
export function visibleWidth(text: string): number {
return text.replace(ANSI_RE, "").length;
@@ -16,8 +17,7 @@ export function truncate(text: string, width: number): string {
let count = 0;
for (let index = 0; index < text.length && count < width; index++) {
if (text[index] === "\x1b") {
// eslint-disable-next-line no-control-regex
const match = text.slice(index).match(new RegExp("^\\u001b\\[[0-9;]*m"));
const match = text.slice(index).match(ANSI_PREFIX_RE);
if (match) {
output += match[0];
index += match[0].length - 1;