ansi-quantone 0.0.0-stage → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +48 -2
- package/dst/ansi-quantone-api-color.d.ts +10 -0
- package/dst/ansi-quantone-api-color.js +44 -0
- package/dst/ansi-quantone-api-debug.d.ts +26 -0
- package/dst/ansi-quantone-api-debug.js +279 -0
- package/dst/ansi-quantone-api-mapping.d.ts +32 -0
- package/dst/ansi-quantone-api-mapping.js +55 -0
- package/dst/ansi-quantone-api-sgr.d.ts +30 -0
- package/dst/ansi-quantone-api-sgr.js +150 -0
- package/dst/ansi-quantone-api-stream.d.ts +7 -0
- package/dst/ansi-quantone-api-stream.js +194 -0
- package/dst/ansi-quantone-api-terminal.d.ts +14 -0
- package/dst/ansi-quantone-api-terminal.js +142 -0
- package/dst/ansi-quantone-api-types.d.ts +28 -0
- package/dst/ansi-quantone-api-types.js +6 -0
- package/dst/ansi-quantone-api.3 +87 -0
- package/dst/ansi-quantone-api.d.ts +11 -0
- package/dst/ansi-quantone-api.js +196 -0
- package/dst/ansi-quantone-cli.d.ts +7 -0
- package/dst/ansi-quantone-cli.js +256 -0
- package/dst/ansi-quantone.1 +123 -0
- package/etc/ansi-quantone.yaml +39 -0
- package/etc/eslint.mjs +81 -0
- package/etc/stx.conf +40 -0
- package/etc/tsc.json +25 -0
- package/package.json +57 -5
- package/src/ansi-quantone-api-color.ts +48 -0
- package/src/ansi-quantone-api-debug.ts +300 -0
- package/src/ansi-quantone-api-mapping.ts +77 -0
- package/src/ansi-quantone-api-sgr.ts +183 -0
- package/src/ansi-quantone-api-stream.ts +207 -0
- package/src/ansi-quantone-api-terminal.ts +156 -0
- package/src/ansi-quantone-api-types.ts +40 -0
- package/src/ansi-quantone-api.md +185 -0
- package/src/ansi-quantone-api.ts +223 -0
- package/src/ansi-quantone-cli.md +212 -0
- package/src/ansi-quantone-cli.ts +259 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { quantone, type QuantoneOptions, type QuantoneColor } from "quantone"
|
|
8
|
+
|
|
9
|
+
import type { InputColor, ColorSpec, ColorMapping } from "./ansi-quantone-api-mapping.js"
|
|
10
|
+
import { classifyColor, rgbToOKLab } from "./ansi-quantone-api-color.js"
|
|
11
|
+
|
|
12
|
+
/* ==== ANSI SGR color transformation ==== */
|
|
13
|
+
|
|
14
|
+
/* the recoloring context */
|
|
15
|
+
export type Recolor = {
|
|
16
|
+
options: QuantoneOptions /* palette options */
|
|
17
|
+
fgSGR: number[] | null /* SGR parameters of mapped default foreground */
|
|
18
|
+
bgOSC: string | null /* OSC 11 sequence of mapped default background */
|
|
19
|
+
defaults: Buffer /* SGR/OSC sequences of both mapped defaults */
|
|
20
|
+
ansi: string[] /* RGB colors of the ANSI colors 0-255 */
|
|
21
|
+
lab: [ number, number, number ][] | null /* OKLab colors of the ANSI colors (if reducing) */
|
|
22
|
+
reduced: Map<number, number> /* cache of RGB colors reduced onto ANSI colors */
|
|
23
|
+
mappings: ColorMapping[] /* color mapping rules */
|
|
24
|
+
src: { fg: InputColor, bg: InputColor } /* current source colors (after reduction) */
|
|
25
|
+
dst: { fg: InputColor, bg: InputColor } /* current target colors (after mapping) */
|
|
26
|
+
buf: Buffer /* buffered incomplete escape sequence */
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/* map a color onto the palette and return its truecolor SGR parameters */
|
|
30
|
+
export const mapColor = (options: QuantoneOptions, color: QuantoneColor, kind: "fg" | "bg"): number[] => {
|
|
31
|
+
const n = parseInt(quantone(options, color).substring(1), 16)
|
|
32
|
+
return [ kind === "fg" ? 38 : 48, 2, (n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF ]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/* reduce an RGB color onto the perceptually nearest ANSI color index */
|
|
36
|
+
const reduceColor = (rc: Recolor, lab: [ number, number, number ][], rgb: number): number => {
|
|
37
|
+
let index = rc.reduced.get(rgb)
|
|
38
|
+
if (index === undefined) {
|
|
39
|
+
const [ L, A, B ] = rgbToOKLab(rgb)
|
|
40
|
+
let best = Infinity
|
|
41
|
+
index = 0
|
|
42
|
+
for (let i = 0; i < lab.length; i++) {
|
|
43
|
+
const d = (L - lab[i][0]) ** 2 + (A - lab[i][1]) ** 2 + (B - lab[i][2]) ** 2
|
|
44
|
+
if (d < best) {
|
|
45
|
+
best = d
|
|
46
|
+
index = i
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (rc.reduced.size >= 4096)
|
|
50
|
+
rc.reduced.clear()
|
|
51
|
+
rc.reduced.set(rgb, index)
|
|
52
|
+
}
|
|
53
|
+
return index
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/* check whether a color of a mapping rule matches an input color */
|
|
57
|
+
const matchColor = (rc: Recolor, spec: ColorSpec, color: InputColor): boolean => {
|
|
58
|
+
switch (spec.type) {
|
|
59
|
+
case "wildcard": return true
|
|
60
|
+
case "default": return color.type === "default"
|
|
61
|
+
case "index": return color.type === "index" && color.index === spec.index
|
|
62
|
+
case "rgb": return color.type === "rgb" && color.rgb === spec.rgb
|
|
63
|
+
case "range": return color.type === "index" && color.index >= spec.from && color.index <= spec.to
|
|
64
|
+
case "class": {
|
|
65
|
+
if (color.type === "default")
|
|
66
|
+
return false
|
|
67
|
+
const cls = classifyColor(color.type === "index" ? parseInt(rc.ansi[color.index].substring(1), 16) : color.rgb)
|
|
68
|
+
return (spec.family === null || spec.family === cls.family)
|
|
69
|
+
&& (spec.tone === null || spec.tone === cls.tone)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/* check whether two input colors are the same */
|
|
75
|
+
const sameColor = (a: InputColor, b: InputColor): boolean =>
|
|
76
|
+
(a.type === "default" && b.type === "default")
|
|
77
|
+
|| (a.type === "index" && b.type === "index" && a.index === b.index)
|
|
78
|
+
|| (a.type === "rgb" && b.type === "rgb" && a.rgb === b.rgb)
|
|
79
|
+
|
|
80
|
+
/* map an input color onto the palette and return its SGR parameters
|
|
81
|
+
(where the default foreground gets the mapped default foreground, if any) */
|
|
82
|
+
const colorSGR = (rc: Recolor, color: InputColor, kind: "fg" | "bg"): number[] => {
|
|
83
|
+
if (color.type === "default")
|
|
84
|
+
return kind === "fg" ? (rc.fgSGR ?? [ 39 ]) : [ 49 ]
|
|
85
|
+
const hex = color.type === "index" ? rc.ansi[color.index] : "#" + color.rgb.toString(16).padStart(6, "0")
|
|
86
|
+
return mapColor(rc.options, hex, kind)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* reset the current source and target colors to the terminal default colors */
|
|
90
|
+
export const resetColors = (rc: Recolor): void => {
|
|
91
|
+
rc.src = { fg: { type: "default" }, bg: { type: "default" } }
|
|
92
|
+
rc.dst = { fg: { type: "default" }, bg: { type: "default" } }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/* transform an SGR parameter sequence, rewriting all colors onto the palette:
|
|
96
|
+
track the current source colors (with RGB colors optionally reduced onto ANSI colors),
|
|
97
|
+
apply the mapping rules (last match wins), and emit the target colors after all
|
|
98
|
+
non-color attributes (which are passed through unchanged) -- the colors set by
|
|
99
|
+
the sequence always, the other ones only if their mapping changed */
|
|
100
|
+
export const transformSGR = (params: number[], rc: Recolor): number[] => {
|
|
101
|
+
const result: number[] = []
|
|
102
|
+
const set = { fg: false, bg: false }
|
|
103
|
+
let changed = false
|
|
104
|
+
const setColor = (kind: "fg" | "bg", color: InputColor) => {
|
|
105
|
+
rc.src[kind] = color
|
|
106
|
+
set[kind] = true
|
|
107
|
+
changed = true
|
|
108
|
+
}
|
|
109
|
+
let i = 0
|
|
110
|
+
while (i < params.length) {
|
|
111
|
+
const p = params[i]
|
|
112
|
+
if (p === 0) {
|
|
113
|
+
/* reset: re-establish the mapped default foreground, if any */
|
|
114
|
+
result.push(0)
|
|
115
|
+
resetColors(rc)
|
|
116
|
+
set.fg = rc.fgSGR !== null
|
|
117
|
+
set.bg = false
|
|
118
|
+
changed = true
|
|
119
|
+
i++
|
|
120
|
+
}
|
|
121
|
+
else if (p === 39 || p === 49) {
|
|
122
|
+
/* default color */
|
|
123
|
+
setColor(p === 39 ? "fg" : "bg", { type: "default" })
|
|
124
|
+
i++
|
|
125
|
+
}
|
|
126
|
+
else if ((p >= 30 && p <= 37) || (p >= 40 && p <= 47)) {
|
|
127
|
+
/* basic color: ANSI color index 0-7 */
|
|
128
|
+
setColor(p < 40 ? "fg" : "bg", { type: "index", index: p % 10 })
|
|
129
|
+
i++
|
|
130
|
+
}
|
|
131
|
+
else if ((p >= 90 && p <= 97) || (p >= 100 && p <= 107)) {
|
|
132
|
+
/* bright color: ANSI color index 8-15 */
|
|
133
|
+
setColor(p < 100 ? "fg" : "bg", { type: "index", index: p % 10 + 8 })
|
|
134
|
+
i++
|
|
135
|
+
}
|
|
136
|
+
else if ((p === 38 || p === 48) && params[i + 1] === 5
|
|
137
|
+
&& i + 2 < params.length && params[i + 2] <= 255) {
|
|
138
|
+
/* 256-color: ANSI color index 0-255 */
|
|
139
|
+
setColor(p === 38 ? "fg" : "bg", { type: "index", index: params[i + 2] })
|
|
140
|
+
i += 3
|
|
141
|
+
}
|
|
142
|
+
else if ((p === 38 || p === 48) && params[i + 1] === 2
|
|
143
|
+
&& i + 4 < params.length && params[i + 2] <= 255 && params[i + 3] <= 255 && params[i + 4] <= 255) {
|
|
144
|
+
/* RGB/truecolor (optionally reduced onto the nearest ANSI color) */
|
|
145
|
+
const rgb = (params[i + 2] << 16) | (params[i + 3] << 8) | params[i + 4]
|
|
146
|
+
setColor(p === 38 ? "fg" : "bg", rc.lab !== null ?
|
|
147
|
+
{ type: "index", index: reduceColor(rc, rc.lab, rgb) } : { type: "rgb", rgb })
|
|
148
|
+
i += 5
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
/* non-color attribute or malformed extended color */
|
|
152
|
+
result.push(p)
|
|
153
|
+
i++
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!changed)
|
|
157
|
+
return result
|
|
158
|
+
|
|
159
|
+
/* apply the mapping rules (all matching ones in order, so the last match wins) */
|
|
160
|
+
let { fg, bg } = rc.src
|
|
161
|
+
for (const rule of rc.mappings) {
|
|
162
|
+
if (matchColor(rc, rule.fromFg, rc.src.fg) && matchColor(rc, rule.fromBg, rc.src.bg)) {
|
|
163
|
+
if (rule.toFg.type !== "wildcard")
|
|
164
|
+
fg = rule.toFg as InputColor
|
|
165
|
+
if (rule.toBg.type !== "wildcard")
|
|
166
|
+
bg = rule.toBg as InputColor
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/* emit the target colors */
|
|
171
|
+
for (const [ kind, color ] of [ [ "fg", fg ], [ "bg", bg ] ] as const) {
|
|
172
|
+
if (set[kind] || !sameColor(color, rc.dst[kind])) {
|
|
173
|
+
result.push(...colorSGR(rc, color, kind))
|
|
174
|
+
rc.dst[kind] = color
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return result
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/* determine whether a string command sets (OSC 11) or resets (OSC 111) the default background */
|
|
181
|
+
export const isBgChange = (seq: Buffer): boolean =>
|
|
182
|
+
/^\x1b\](?:11;(?!\?)|111(?:;|\x07|\x1b))/.test(seq.toString("latin1"))
|
|
183
|
+
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { type Recolor, transformSGR, resetColors, isBgChange } from "./ansi-quantone-api-sgr.js"
|
|
8
|
+
|
|
9
|
+
/* ==== stream processing with partial sequence buffering ==== */
|
|
10
|
+
|
|
11
|
+
/* parser states for the escape sequence state machine */
|
|
12
|
+
const S_NORMAL = 0 /* plain text, scanning for ESC */
|
|
13
|
+
const S_ESC = 1 /* just saw ESC, determining sequence type */
|
|
14
|
+
const S_ESC_INTER = 2 /* ESC + intermediate bytes (nF sequence) */
|
|
15
|
+
const S_CSI_PARAM = 3 /* CSI parameter bytes */
|
|
16
|
+
const S_CSI_INTER = 4 /* CSI intermediate bytes */
|
|
17
|
+
const S_STR_BODY = 5 /* string command body (OSC/DCS/APC/PM/SOS) */
|
|
18
|
+
const S_STR_ESC = 6 /* ESC inside string command (potential ST) */
|
|
19
|
+
|
|
20
|
+
/* process a raw byte chunk through the escape sequence state machine
|
|
21
|
+
(operates on raw bytes so UTF-8 multi-byte sequences are never decoded/buffered;
|
|
22
|
+
ESC and all escape sequence bytes are in the ASCII range 0x00-0x7F which never
|
|
23
|
+
overlaps with UTF-8 continuation bytes 0x80-0xBF, so raw scanning is safe) */
|
|
24
|
+
export const processChunk = (chunk: Buffer, rc: Recolor): Buffer => {
|
|
25
|
+
const buf = rc.buf.length === 0 ? chunk : Buffer.concat([ rc.buf, chunk ])
|
|
26
|
+
const out: Buffer[] = []
|
|
27
|
+
let i = 0
|
|
28
|
+
let seqStart = -1
|
|
29
|
+
let state = S_NORMAL
|
|
30
|
+
|
|
31
|
+
while (i < buf.length) {
|
|
32
|
+
const ch = buf[i]
|
|
33
|
+
switch (state) {
|
|
34
|
+
case S_NORMAL: {
|
|
35
|
+
/* fast-scan for next ESC byte */
|
|
36
|
+
const escIdx = buf.indexOf(0x1B, i)
|
|
37
|
+
if (escIdx === -1) {
|
|
38
|
+
out.push(buf.subarray(i))
|
|
39
|
+
i = buf.length
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
if (escIdx > i)
|
|
43
|
+
out.push(buf.subarray(i, escIdx))
|
|
44
|
+
seqStart = escIdx
|
|
45
|
+
state = S_ESC
|
|
46
|
+
i = escIdx + 1
|
|
47
|
+
}
|
|
48
|
+
break
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
case S_ESC:
|
|
52
|
+
if (ch === 0x5B) {
|
|
53
|
+
/* "[" → CSI sequence */
|
|
54
|
+
state = S_CSI_PARAM
|
|
55
|
+
i++
|
|
56
|
+
}
|
|
57
|
+
else if (ch === 0x5D || ch === 0x50 || ch === 0x5F
|
|
58
|
+
|| ch === 0x5E || ch === 0x58) {
|
|
59
|
+
/* "]" / "P" / "_" / "^" / "X" → string command */
|
|
60
|
+
state = S_STR_BODY
|
|
61
|
+
i++
|
|
62
|
+
}
|
|
63
|
+
else if (ch >= 0x20 && ch <= 0x2F) {
|
|
64
|
+
/* intermediate byte → nF escape sequence */
|
|
65
|
+
state = S_ESC_INTER
|
|
66
|
+
i++
|
|
67
|
+
}
|
|
68
|
+
else if (ch >= 0x30 && ch <= 0x7E) {
|
|
69
|
+
/* final byte → simple two-byte ESC sequence
|
|
70
|
+
(after "c" (RIS) re-establish the mapped default colors) */
|
|
71
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
72
|
+
if (ch === 0x63) {
|
|
73
|
+
out.push(rc.defaults)
|
|
74
|
+
resetColors(rc)
|
|
75
|
+
}
|
|
76
|
+
state = S_NORMAL
|
|
77
|
+
i++
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
/* unexpected byte → flush ESC and re-process */
|
|
81
|
+
out.push(buf.subarray(seqStart, seqStart + 1))
|
|
82
|
+
state = S_NORMAL
|
|
83
|
+
i = seqStart + 1
|
|
84
|
+
}
|
|
85
|
+
break
|
|
86
|
+
|
|
87
|
+
case S_ESC_INTER:
|
|
88
|
+
if (ch >= 0x20 && ch <= 0x2F) {
|
|
89
|
+
/* more intermediate bytes */
|
|
90
|
+
i++
|
|
91
|
+
}
|
|
92
|
+
else if (ch >= 0x30 && ch <= 0x7E) {
|
|
93
|
+
/* final byte → complete nF sequence */
|
|
94
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
95
|
+
state = S_NORMAL
|
|
96
|
+
i++
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
/* unexpected → flush and re-process */
|
|
100
|
+
out.push(buf.subarray(seqStart, i))
|
|
101
|
+
state = S_NORMAL
|
|
102
|
+
}
|
|
103
|
+
break
|
|
104
|
+
|
|
105
|
+
case S_CSI_PARAM:
|
|
106
|
+
if (ch >= 0x30 && ch <= 0x3F) {
|
|
107
|
+
/* parameter byte (digits, ";", "?", ">", etc.) */
|
|
108
|
+
i++
|
|
109
|
+
}
|
|
110
|
+
else if (ch >= 0x20 && ch <= 0x2F) {
|
|
111
|
+
/* intermediate byte */
|
|
112
|
+
state = S_CSI_INTER
|
|
113
|
+
i++
|
|
114
|
+
}
|
|
115
|
+
else if (ch >= 0x40 && ch <= 0x7E) {
|
|
116
|
+
/* final byte → CSI sequence complete */
|
|
117
|
+
if (ch === 0x6D) {
|
|
118
|
+
/* "m" → SGR: transform colors */
|
|
119
|
+
const paramStr = buf.subarray(seqStart + 2, i).toString("ascii")
|
|
120
|
+
if (/^[0-9;]*$/.test(paramStr)) {
|
|
121
|
+
const params = paramStr === "" ? [ 0 ] : paramStr.split(";").map(Number)
|
|
122
|
+
const mapped = transformSGR(params, rc)
|
|
123
|
+
out.push(Buffer.from(`\x1b[${mapped.join(";")}m`))
|
|
124
|
+
}
|
|
125
|
+
else
|
|
126
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
127
|
+
}
|
|
128
|
+
else
|
|
129
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
130
|
+
state = S_NORMAL
|
|
131
|
+
i++
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
/* unexpected → flush and re-process */
|
|
135
|
+
out.push(buf.subarray(seqStart, i))
|
|
136
|
+
state = S_NORMAL
|
|
137
|
+
}
|
|
138
|
+
break
|
|
139
|
+
|
|
140
|
+
case S_CSI_INTER:
|
|
141
|
+
if (ch >= 0x20 && ch <= 0x2F) {
|
|
142
|
+
/* more intermediate bytes */
|
|
143
|
+
i++
|
|
144
|
+
}
|
|
145
|
+
else if (ch >= 0x40 && ch <= 0x7E) {
|
|
146
|
+
/* final byte → CSI sequence complete (non-SGR)
|
|
147
|
+
(after "CSI ! p" (DECSTR) re-establish the mapped default colors) */
|
|
148
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
149
|
+
if (ch === 0x70 && buf.subarray(seqStart + 2, i).toString("ascii") === "!") {
|
|
150
|
+
out.push(rc.defaults)
|
|
151
|
+
resetColors(rc)
|
|
152
|
+
}
|
|
153
|
+
state = S_NORMAL
|
|
154
|
+
i++
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
/* unexpected → flush and re-process */
|
|
158
|
+
out.push(buf.subarray(seqStart, i))
|
|
159
|
+
state = S_NORMAL
|
|
160
|
+
}
|
|
161
|
+
break
|
|
162
|
+
|
|
163
|
+
case S_STR_BODY:
|
|
164
|
+
if (ch === 0x1B) {
|
|
165
|
+
/* ESC inside string command → potential ST */
|
|
166
|
+
state = S_STR_ESC
|
|
167
|
+
i++
|
|
168
|
+
}
|
|
169
|
+
else if (ch === 0x07) {
|
|
170
|
+
/* BEL terminates string commands (at least OSC)
|
|
171
|
+
(suppress default background changes while it is mapped) */
|
|
172
|
+
if (rc.bgOSC === null || !isBgChange(buf.subarray(seqStart, i + 1)))
|
|
173
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
174
|
+
state = S_NORMAL
|
|
175
|
+
i++
|
|
176
|
+
}
|
|
177
|
+
else
|
|
178
|
+
i++
|
|
179
|
+
break
|
|
180
|
+
|
|
181
|
+
case S_STR_ESC:
|
|
182
|
+
if (ch === 0x5C) {
|
|
183
|
+
/* "\" → ST (String Terminator) → string command complete
|
|
184
|
+
(suppress default background changes while it is mapped) */
|
|
185
|
+
if (rc.bgOSC === null || !isBgChange(buf.subarray(seqStart, i + 1)))
|
|
186
|
+
out.push(buf.subarray(seqStart, i + 1))
|
|
187
|
+
state = S_NORMAL
|
|
188
|
+
i++
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
/* not ST → ESC starts a new sequence (malformed input) */
|
|
192
|
+
out.push(buf.subarray(seqStart, i - 1))
|
|
193
|
+
seqStart = i - 1
|
|
194
|
+
state = S_ESC
|
|
195
|
+
}
|
|
196
|
+
break
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* keep any incomplete escape sequence in the buffer */
|
|
201
|
+
if (state !== S_NORMAL)
|
|
202
|
+
rc.buf = Buffer.from(buf.subarray(seqStart))
|
|
203
|
+
else
|
|
204
|
+
rc.buf = Buffer.alloc(0)
|
|
205
|
+
return Buffer.concat(out)
|
|
206
|
+
}
|
|
207
|
+
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import process from "node:process"
|
|
8
|
+
import crypto from "node:crypto"
|
|
9
|
+
import fs from "node:fs"
|
|
10
|
+
import os from "node:os"
|
|
11
|
+
import path from "node:path"
|
|
12
|
+
import { spawnSync } from "node:child_process"
|
|
13
|
+
|
|
14
|
+
import ttyAttr from "tty-attr"
|
|
15
|
+
|
|
16
|
+
import type { TerminalIO } from "./ansi-quantone-api-types.js"
|
|
17
|
+
|
|
18
|
+
/* ==== terminal color query ==== */
|
|
19
|
+
|
|
20
|
+
/* the canonical xterm RGB values of the ANSI colors 0-255
|
|
21
|
+
(the fallbacks for the colors not reported by the terminal) */
|
|
22
|
+
export const xtermColors = Array.from({ length: 256 }, (_, i): string => {
|
|
23
|
+
const level = (v: number) => v === 0 ? 0 : 55 + 40 * v
|
|
24
|
+
let n: number
|
|
25
|
+
if (i < 16)
|
|
26
|
+
n = [ 0x000000, 0xcd0000, 0x00cd00, 0xcdcd00, 0x0000ee, 0xcd00cd, 0x00cdcd, 0xe5e5e5,
|
|
27
|
+
0x7f7f7f, 0xff0000, 0x00ff00, 0xffff00, 0x5c5cff, 0xff00ff, 0x00ffff, 0xffffff ][i]
|
|
28
|
+
else if (i < 232)
|
|
29
|
+
n = (level(Math.floor((i - 16) / 36)) << 16) | (level(Math.floor((i - 16) / 6) % 6) << 8) | level((i - 16) % 6)
|
|
30
|
+
else
|
|
31
|
+
n = (8 + 10 * (i - 232)) * 0x010101
|
|
32
|
+
return "#" + n.toString(16).padStart(6, "0")
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
/* query the terminal colors via OSC 4 (ANSI color "4;<n>"), OSC 10 (default foreground
|
|
36
|
+
"10"), and OSC 11 (default background "11"), terminated by a DA1 query which every
|
|
37
|
+
terminal answers, and return the received colors plus all other received input bytes */
|
|
38
|
+
export const queryColors = (terminal: TerminalIO, codes: string[]): Promise<{ colors: Map<string, string>, rest: Buffer }> => {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
let data = ""
|
|
41
|
+
const finish = () => {
|
|
42
|
+
clearTimeout(timer)
|
|
43
|
+
offData()
|
|
44
|
+
const colors = new Map<string, string>()
|
|
45
|
+
const re = /\x1b\]((?:4;)?\d+);rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(?:\x07|\x1b\\)/g
|
|
46
|
+
for (const m of data.matchAll(re)) {
|
|
47
|
+
/* scale each 1-4 digit hex channel onto 8 bits */
|
|
48
|
+
const hex = m.slice(2, 5).map((c) =>
|
|
49
|
+
Math.round(parseInt(c, 16) / (16 ** c.length - 1) * 255).toString(16).padStart(2, "0"))
|
|
50
|
+
colors.set(m[1], "#" + hex.join(""))
|
|
51
|
+
}
|
|
52
|
+
const rest = data.replace(re, "").replace(/\x1b\[\?[0-9;]*c/, "")
|
|
53
|
+
resolve({ colors, rest: Buffer.from(rest, "latin1") })
|
|
54
|
+
}
|
|
55
|
+
const onData = (chunk: Buffer) => {
|
|
56
|
+
data += chunk.toString("latin1")
|
|
57
|
+
if (/\x1b\[\?[0-9;]*c/.test(data))
|
|
58
|
+
finish()
|
|
59
|
+
}
|
|
60
|
+
const timer = setTimeout(finish, 1000)
|
|
61
|
+
const offData = terminal.onData(onData)
|
|
62
|
+
terminal.write(codes.map((code) => `\x1b]${code};?\x1b\\`).join("") + "\x1b[c")
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/* load the cached terminal colors (or none on a missing or broken cache file) */
|
|
67
|
+
export const loadColors = (file: string): Map<string, string> => {
|
|
68
|
+
try {
|
|
69
|
+
const data: unknown = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
70
|
+
if (typeof data !== "object" || data === null || Array.isArray(data))
|
|
71
|
+
return new Map()
|
|
72
|
+
return new Map(Object.entries(data).filter((entry): entry is [ string, string ] =>
|
|
73
|
+
typeof entry[1] === "string" && /^#[0-9a-f]{6}$/.test(entry[1])))
|
|
74
|
+
}
|
|
75
|
+
catch (_err: unknown) {
|
|
76
|
+
return new Map()
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/* save the queried terminal colors over the cached ones (ignoring any failures),
|
|
81
|
+
atomically via a temporary file, so concurrent runs never read a partial file */
|
|
82
|
+
export const saveColors = (file: string, colors: Map<string, string>): void => {
|
|
83
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
84
|
+
try {
|
|
85
|
+
const merged = new Map([ ...loadColors(file), ...colors ])
|
|
86
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
87
|
+
fs.writeFileSync(temp, JSON.stringify(Object.fromEntries(merged)) + "\n", { mode: 0o600 })
|
|
88
|
+
fs.renameSync(temp, file)
|
|
89
|
+
}
|
|
90
|
+
catch (_err: unknown) {
|
|
91
|
+
try { fs.unlinkSync(temp) }
|
|
92
|
+
catch (_err2: unknown) { /* ignore */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ==== process stdio terminal ==== */
|
|
97
|
+
|
|
98
|
+
/* determine the cache file of the queried colors of the process stdio terminal: only within
|
|
99
|
+
tmux, where e.g. popups do not answer color queries, and per tmux client (as identified by
|
|
100
|
+
the server socket and the client PID), as each client can be a different terminal */
|
|
101
|
+
const cacheFile = (): string | undefined => {
|
|
102
|
+
const tmux = process.env.TMUX ?? ""
|
|
103
|
+
if (tmux === "")
|
|
104
|
+
return undefined
|
|
105
|
+
const result = spawnSync("tmux", [ "display-message", "-p", "#{client_pid}" ],
|
|
106
|
+
{ encoding: "utf8", stdio: [ "ignore", "pipe", "ignore" ], timeout: 2000 })
|
|
107
|
+
const client = result.status === 0 ? result.stdout.trim() : ""
|
|
108
|
+
if (!/^\d+$/.test(client))
|
|
109
|
+
return undefined
|
|
110
|
+
const socket = tmux.replace(/,\d+,\d+$/, "")
|
|
111
|
+
const dir = path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"), "ansi-quantone")
|
|
112
|
+
const key = crypto.createHash("sha1").update(`${socket}:${client}`).digest("hex").substring(0, 16)
|
|
113
|
+
return path.join(dir, `colors-tmux-${key}.json`)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/* the terminal I/O of the process stdio (the default terminal of a recoloring run) */
|
|
117
|
+
export const stdioTerminal = (): TerminalIO => ({
|
|
118
|
+
query: process.stdin.isTTY === true,
|
|
119
|
+
cache: cacheFile(),
|
|
120
|
+
columns: () => process.stdout.columns ?? 80,
|
|
121
|
+
rows: () => process.stdout.rows ?? 24,
|
|
122
|
+
write: (data, cb) => process.stdout.write(data, cb),
|
|
123
|
+
onDrain: (cb) => { process.stdout.once("drain", cb) },
|
|
124
|
+
onData: (cb) => {
|
|
125
|
+
process.stdin.on("data", cb)
|
|
126
|
+
process.stdin.resume()
|
|
127
|
+
return () => {
|
|
128
|
+
process.stdin.off("data", cb)
|
|
129
|
+
process.stdin.pause()
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
onResize: (cb) => {
|
|
133
|
+
process.stdout.on("resize", cb)
|
|
134
|
+
return () => { process.stdout.off("resize", cb) }
|
|
135
|
+
},
|
|
136
|
+
onSignal: (cb) => {
|
|
137
|
+
const handlers = ([ "SIGTERM", "SIGHUP" ] as const).map((signal) => [ signal, () => { cb(signal) } ] as const)
|
|
138
|
+
for (const [ signal, handler ] of handlers)
|
|
139
|
+
process.on(signal, handler)
|
|
140
|
+
return () => {
|
|
141
|
+
for (const [ signal, handler ] of handlers)
|
|
142
|
+
process.off(signal, handler)
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
setup: () => {
|
|
146
|
+
if (process.stdin.isTTY) {
|
|
147
|
+
ttyAttr.preserveAttr()
|
|
148
|
+
ttyAttr.setRawMode()
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
restore: () => {
|
|
152
|
+
if (process.stdin.isTTY)
|
|
153
|
+
ttyAttr.restoreAttr()
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { QuantoneOptions, QuantoneColor } from "quantone"
|
|
8
|
+
|
|
9
|
+
/* ==== API types ==== */
|
|
10
|
+
|
|
11
|
+
/* the input color of a terminal default color: a color, "auto" (query terminal), or "none" */
|
|
12
|
+
export type DefaultColor = QuantoneColor | "auto" | "none"
|
|
13
|
+
|
|
14
|
+
/* the entire configuration */
|
|
15
|
+
export type Config = {
|
|
16
|
+
palette: QuantoneOptions /* palette options of Quantone */
|
|
17
|
+
foreground: DefaultColor /* input color of the terminal default foreground */
|
|
18
|
+
background: DefaultColor /* input color of the terminal default background */
|
|
19
|
+
reduce: boolean /* reduce RGB/truecolor input colors onto ANSI colors */
|
|
20
|
+
mappings: string[] /* color mapping rules "<fg>/<bg> : <fg>/<bg>" */
|
|
21
|
+
debug: boolean /* enable debug mode */
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/* the terminal I/O of a recoloring run (e.g. the process stdio,
|
|
25
|
+
or a bridge to the terminal of a Web UI), where all "on*" functions
|
|
26
|
+
register a callback and return a function to unregister it again */
|
|
27
|
+
export type TerminalIO = {
|
|
28
|
+
query: boolean /* whether it answers queries */
|
|
29
|
+
cache?: string /* cache file of queried colors */
|
|
30
|
+
columns: () => number /* current number of columns */
|
|
31
|
+
rows: () => number /* current number of rows */
|
|
32
|
+
write: (data: Buffer | string, cb?: () => void) => boolean /* write output (false: full) */
|
|
33
|
+
onDrain: (cb: () => void) => void /* once output drained again */
|
|
34
|
+
onData: (cb: (data: Buffer) => void) => () => void /* on input data */
|
|
35
|
+
onResize: (cb: () => void) => () => void /* on terminal size changes */
|
|
36
|
+
onSignal: (cb: (signal: "SIGTERM" | "SIGHUP") => void) => () => void /* on termination */
|
|
37
|
+
setup: () => void /* switch into raw mode */
|
|
38
|
+
restore: () => void /* restore original mode */
|
|
39
|
+
}
|
|
40
|
+
|