ansi-quantone 0.0.0-stage → 0.9.0

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +48 -2
  3. package/dst/ansi-quantone-api-color.d.ts +10 -0
  4. package/dst/ansi-quantone-api-color.js +44 -0
  5. package/dst/ansi-quantone-api-debug.d.ts +26 -0
  6. package/dst/ansi-quantone-api-debug.js +279 -0
  7. package/dst/ansi-quantone-api-mapping.d.ts +32 -0
  8. package/dst/ansi-quantone-api-mapping.js +55 -0
  9. package/dst/ansi-quantone-api-sgr.d.ts +30 -0
  10. package/dst/ansi-quantone-api-sgr.js +150 -0
  11. package/dst/ansi-quantone-api-stream.d.ts +7 -0
  12. package/dst/ansi-quantone-api-stream.js +194 -0
  13. package/dst/ansi-quantone-api-terminal.d.ts +12 -0
  14. package/dst/ansi-quantone-api-terminal.js +91 -0
  15. package/dst/ansi-quantone-api-types.d.ts +27 -0
  16. package/dst/ansi-quantone-api-types.js +6 -0
  17. package/dst/ansi-quantone-api.3 +85 -0
  18. package/dst/ansi-quantone-api.d.ts +11 -0
  19. package/dst/ansi-quantone-api.js +188 -0
  20. package/dst/ansi-quantone-cli.d.ts +7 -0
  21. package/dst/ansi-quantone-cli.js +256 -0
  22. package/dst/ansi-quantone.1 +123 -0
  23. package/etc/ansi-quantone.yaml +39 -0
  24. package/etc/eslint.mjs +81 -0
  25. package/etc/stx.conf +40 -0
  26. package/etc/tsc.json +25 -0
  27. package/package.json +57 -5
  28. package/src/ansi-quantone-api-color.ts +48 -0
  29. package/src/ansi-quantone-api-debug.ts +300 -0
  30. package/src/ansi-quantone-api-mapping.ts +77 -0
  31. package/src/ansi-quantone-api-sgr.ts +183 -0
  32. package/src/ansi-quantone-api-stream.ts +207 -0
  33. package/src/ansi-quantone-api-terminal.ts +102 -0
  34. package/src/ansi-quantone-api-types.ts +39 -0
  35. package/src/ansi-quantone-api.md +175 -0
  36. package/src/ansi-quantone-api.ts +214 -0
  37. package/src/ansi-quantone-cli.md +211 -0
  38. package/src/ansi-quantone-cli.ts +259 -0
package/etc/eslint.mjs ADDED
@@ -0,0 +1,81 @@
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 pluginJs from "@eslint/js"
8
+ import pluginStd from "neostandard"
9
+ import pluginImport from "eslint-plugin-import"
10
+ import pluginPromise from "eslint-plugin-promise"
11
+ import pluginTS from "typescript-eslint"
12
+ import globals from "globals"
13
+ import parserTS from "@typescript-eslint/parser"
14
+
15
+ export default [
16
+ pluginJs.configs.recommended,
17
+ ...pluginTS.configs.strict,
18
+ ...pluginTS.configs.stylistic,
19
+ ...pluginStd({
20
+ ts: true,
21
+ ignores: pluginStd.resolveIgnoresFromGitignore()
22
+ }),
23
+ {
24
+ plugins: {
25
+ "import": pluginImport,
26
+ "promise": pluginPromise
27
+ },
28
+ files: [ "src/**/*.ts" ],
29
+ languageOptions: {
30
+ ecmaVersion: 2022,
31
+ sourceType: "module",
32
+ parser: parserTS,
33
+ parserOptions: {
34
+ ecmaFeatures: {
35
+ jsx: false
36
+ }
37
+ },
38
+ globals: {
39
+ ...globals.node,
40
+ ...globals.commonjs
41
+ }
42
+ },
43
+ rules: {
44
+ "curly": "off",
45
+ "require-atomic-updates": "off",
46
+ "dot-notation": "off",
47
+ "no-labels": "off",
48
+ "no-useless-constructor": "off",
49
+ "no-control-regex": "off",
50
+
51
+ "@stylistic/indent": [ "error", 4, { SwitchCase: 1 } ],
52
+ "@stylistic/linebreak-style": [ "error", "unix" ],
53
+ "@stylistic/semi": [ "error", "never" ],
54
+ "@stylistic/operator-linebreak": [ "error", "after", { overrides: { "&&": "before", "||": "before", ":": "after", "|": "ignore", "&": "ignore" } } ],
55
+ "@stylistic/brace-style": [ "error", "stroustrup", { allowSingleLine: true } ],
56
+ "@stylistic/quotes": [ "error", "double" ],
57
+
58
+ "@stylistic/no-multi-spaces": "off",
59
+ "@stylistic/no-multi-spaces": "off",
60
+ "@stylistic/no-multiple-empty-lines": "off",
61
+ "@stylistic/key-spacing": "off",
62
+ "@stylistic/object-property-newline": "off",
63
+ "@stylistic/space-in-parens": "off",
64
+ "@stylistic/array-bracket-spacing": "off",
65
+ "@stylistic/lines-between-class-members": "off",
66
+ "@stylistic/multiline-ternary": "off",
67
+ "@stylistic/quote-props": "off",
68
+
69
+ "@typescript-eslint/no-empty-function": "off",
70
+ "@typescript-eslint/no-explicit-any": "off",
71
+ "@typescript-eslint/no-unused-vars": "off",
72
+ "@typescript-eslint/ban-ts-comment": "off",
73
+ "@typescript-eslint/no-this-alias": "off",
74
+ "@typescript-eslint/no-non-null-assertion": "off",
75
+ "@typescript-eslint/consistent-type-definitions": "off",
76
+ "@typescript-eslint/array-type": "off",
77
+ "@typescript-eslint/no-extraneous-class": "off",
78
+ "@typescript-eslint/consistent-indexed-object-style": "off"
79
+ }
80
+ }
81
+ ]
package/etc/stx.conf ADDED
@@ -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
+ # static code analysis (linting)
8
+ lint
9
+ eslint --config etc/eslint.mjs src/*.ts
10
+
11
+ # static code analysis (linting) with file watching
12
+ lint-watch
13
+ nodemon --exec "npm start lint" --watch src --ext ts
14
+
15
+ # code compilation/transpiling (building) with file watching
16
+ build-watch
17
+ nodemon --exec "npm start build" --watch src --ext ts
18
+
19
+ # build entire project
20
+ build : lint build-cmd build-man
21
+
22
+ # build command program
23
+ build-cmd
24
+ tsc --project etc/tsc.json && \
25
+ chmod 755 dst/ansi-quantone-cli.js
26
+
27
+ # build manual pages
28
+ build-man
29
+ remark --quiet --use remark-man --output dst/ansi-quantone.1 src/ansi-quantone-cli.md && \
30
+ remark --quiet --use remark-man --output dst/ansi-quantone-api.3 src/ansi-quantone-api.md
31
+
32
+ # remove regularly built files
33
+ clean
34
+ shx rm -rf dst
35
+
36
+ # remove all built files
37
+ clean-dist : clean
38
+ shx rm -f package-lock.json
39
+ shx rm -rf node_modules
40
+
package/etc/tsc.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "../dst",
4
+ "target": "esnext",
5
+ "module": "nodenext",
6
+ "moduleResolution": "nodenext",
7
+ "useDefineForClassFields": true,
8
+ "composite": false,
9
+ "strict": true,
10
+ "resolveJsonModule": true,
11
+ "isolatedModules": true,
12
+ "esModuleInterop": true,
13
+ "lib": [ "ESNext" ],
14
+ "skipLibCheck": true,
15
+ "noEmit": false,
16
+ "declaration": true,
17
+ "types": [ "node" ],
18
+ "rootDir": "../src"
19
+ },
20
+ "include": [
21
+ "../src/**/*.ts",
22
+ "../src/**/*.d.ts",
23
+ "../package.json"
24
+ ]
25
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
- "name": "ansi-quantone",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "ansi-quantone",
3
+ "description": "Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette",
4
+ "keywords": [ "ansi", "color", "recolor", "quantize", "palette", "tui" ],
5
+ "version": "0.9.0",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Dr. Ralf S. Engelschall",
9
+ "email": "rse@engelschall.com",
10
+ "url": "http://engelschall.com"
11
+ },
12
+ "type": "module",
13
+ "main": "dst/ansi-quantone-api.js",
14
+ "types": "dst/ansi-quantone-api.d.ts",
15
+ "bin": { "ansi-quantone": "dst/ansi-quantone-cli.js" },
16
+ "devDependencies": {
17
+ "eslint": "9.39.4",
18
+ "@eslint/js": "9.39.4",
19
+ "eslint-plugin-promise": "7.3.0",
20
+ "eslint-plugin-import": "2.32.0",
21
+ "neostandard": "0.14.1",
22
+ "globals": "17.15.0",
23
+ "shx": "0.4.0",
24
+ "typescript": "6.0.3",
25
+ "typescript-eslint": "8.74.0",
26
+ "nodemon": "3.1.14",
27
+ "@rse/stx": "1.1.7",
28
+ "tsx": "4.23.15",
29
+ "remark-cli": "12.0.1",
30
+ "remark": "15.0.1",
31
+ "remark-man": "9.0.0",
32
+
33
+ "@types/node": "26.6.11",
34
+ "@types/yargs": "17.0.35"
35
+ },
36
+ "dependencies": {
37
+ "yargs": "18.2.0",
38
+ "node-pty": "1.2.0-beta.12",
39
+ "@xterm/headless": "6.0.0",
40
+ "tty-attr": "0.9.3",
41
+ "quantone": "0.9.6",
42
+ "yaml": "2.9.1"
43
+ },
44
+ "allowScripts": {
45
+ "esbuild": true,
46
+ "node-pty": true,
47
+ "tty-attr": true
48
+ },
49
+ "upd": [ "!eslint", "!@eslint/js", "!typescript" ],
50
+ "engines": {
51
+ "npm": ">=10.0.0",
52
+ "node": ">=22.0.0"
53
+ },
54
+ "scripts": {
55
+ "start": "stx -v4 -l warning -c etc/stx.conf"
56
+ }
57
+ }
58
+
@@ -0,0 +1,48 @@
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
+ /* ==== color classification and conversion ==== */
8
+
9
+ /* classify an RGB color into its hue family and lightness tone (as in "ansi-recolor"):
10
+ colors with a chroma below 48 are "grey", the others "warm" (hue 280°-60°: magenta, red,
11
+ orange, yellow) or "cool" (hue 60°-280°: green, cyan, blue, violet), and their luma
12
+ (Rec. 709) yields the tone "dark" (below 64), "light" (above 180), or "mid" */
13
+ export const classifyColor = (rgb: number): { family: string, tone: string } => {
14
+ const r = (rgb >> 16) & 0xFF
15
+ const g = (rgb >> 8) & 0xFF
16
+ const b = rgb & 0xFF
17
+ const max = Math.max(r, g, b)
18
+ const min = Math.min(r, g, b)
19
+ const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b
20
+ const tone = luma < 64 ? "dark" : luma > 180 ? "light" : "mid"
21
+ if (max - min < 48)
22
+ return { family: "grey", tone }
23
+ let hue: number
24
+ if (max === r)
25
+ hue = (60 * (g - b) / (max - min) + 360) % 360
26
+ else if (max === g)
27
+ hue = 60 * (b - r) / (max - min) + 120
28
+ else
29
+ hue = 60 * (r - g) / (max - min) + 240
30
+ return { family: hue <= 60 || hue >= 280 ? "warm" : "cool", tone }
31
+ }
32
+
33
+ /* convert an RGB color into the perceptual OKLab color space */
34
+ export const rgbToOKLab = (rgb: number): [ number, number, number ] => {
35
+ const [ r, g, b ] = [ rgb >> 16, rgb >> 8, rgb ].map((v) => {
36
+ const c = (v & 0xFF) / 255
37
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
38
+ })
39
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
40
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
41
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
42
+ return [
43
+ 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
44
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
45
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s
46
+ ]
47
+ }
48
+
@@ -0,0 +1,300 @@
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 { Terminal, IBufferCell } from "@xterm/headless"
8
+
9
+ import type { TerminalIO } from "./ansi-quantone-api-types.js"
10
+
11
+ /* ==== debug mode ==== */
12
+
13
+ /* the debug mode context */
14
+ export type Debug = {
15
+ src: Terminal /* emulated screen of the source output */
16
+ dst: Terminal /* emulated screen of the target output */
17
+ pending: number /* number of still unparsed screen writes */
18
+ prefix: Buffer | null /* CTRL+a prefix key, if it was pressed */
19
+ active: boolean /* whether the debug overlay is displayed */
20
+ x: number /* column of the debug cursor */
21
+ y: number /* row of the debug cursor */
22
+ covered: Set<number> /* screen rows covered by the debug overlay */
23
+ full: boolean /* whether to restore all screen rows */
24
+ ansi: string[] /* RGB colors of the ANSI colors 0-255 */
25
+ hints: Record<string, string> /* hints on the default colors */
26
+ mouse: Map<number, boolean> /* mouse modes of the target screen */
27
+ mouseOn: boolean /* whether the debug mouse mode is enabled */
28
+ output: TerminalIO /* terminal to render the debug overlay onto */
29
+ }
30
+
31
+ /* the DECSET mouse tracking and encoding modes */
32
+ export const mouseModes = [ 9, 1000, 1002, 1003, 1005, 1006, 1015, 1016 ]
33
+
34
+ /* determine a color of a screen cell, as its description and its SGR parameters */
35
+ const cellColor = (cell: IBufferCell | undefined, kind: "fg" | "bg"): { name: string, sgr: number[] } => {
36
+ const base = kind === "fg" ? 30 : 40
37
+ if (cell === undefined || (kind === "fg" ? cell.isFgDefault() : cell.isBgDefault()))
38
+ return { name: "default", sgr: [ base + 9 ] }
39
+ const c = kind === "fg" ? cell.getFgColor() : cell.getBgColor()
40
+ if (kind === "fg" ? cell.isFgPalette() : cell.isBgPalette())
41
+ return { name: `ansi ${c}`, sgr: [ base + 8, 5, c ] }
42
+ return { name: "#" + c.toString(16).padStart(6, "0"), sgr: [ base + 8, 2, (c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF ] }
43
+ }
44
+
45
+ /* determine the SGR sequence of the colors and attributes of a screen cell */
46
+ const cellSGR = (cell: IBufferCell): string => {
47
+ const params = [ 0 ]
48
+ if (cell.isBold()) params.push(1)
49
+ if (cell.isDim()) params.push(2)
50
+ if (cell.isItalic()) params.push(3)
51
+ if (cell.isUnderline()) params.push(4)
52
+ if (cell.isBlink()) params.push(5)
53
+ if (cell.isInverse()) params.push(7)
54
+ if (cell.isInvisible()) params.push(8)
55
+ if (cell.isStrikethrough()) params.push(9)
56
+ if (cell.isOverline()) params.push(53)
57
+ params.push(...cellColor(cell, "fg").sgr, ...cellColor(cell, "bg").sgr)
58
+ return `\x1b[${params.join(";")}m`
59
+ }
60
+
61
+ /* render the debug overlay: restore the previously covered screen rows from the target
62
+ screen and draw the debug cursor and info box anew (with cursor, attributes, charset,
63
+ and origin mode saved/restored by DECSC/DECRC around it), once all output is parsed */
64
+ const debugRender = (dbg: Debug): void => {
65
+ if (dbg.pending > 0)
66
+ return
67
+ const { cols, rows, modes } = dbg.dst
68
+ const bufSrc = dbg.src.buffer.active
69
+ const bufDst = dbg.dst.buffer.active
70
+ let out = "\x1b[?2026h\x1b7\x1b(B\x1b[?6l" + (modes.insertMode ? "\x1b[4l" : "")
71
+
72
+ /* restore the previously covered screen rows (or all of them,
73
+ as output in the meantime could have scrolled the debug overlay) */
74
+ const restore = dbg.full ? Array.from({ length: rows }, (_, y) => y) : [ ...dbg.covered ]
75
+ for (const y of restore) {
76
+ const line = bufDst.getLine(bufDst.baseY + y)
77
+ if (line === undefined)
78
+ continue
79
+ let last = ""
80
+ out += `\x1b[${y + 1};1H`
81
+ for (let x = 0; x < cols; x++) {
82
+ const cell = line.getCell(x)
83
+ if (cell === undefined || cell.getWidth() === 0)
84
+ continue
85
+ const sgr = cellSGR(cell)
86
+ if (sgr !== last)
87
+ out += (last = sgr)
88
+ out += cell.getChars() || " "
89
+ }
90
+ }
91
+ dbg.covered.clear()
92
+ dbg.full = false
93
+
94
+ if (dbg.active) {
95
+ /* determine the observed cell (never the second half of a wide character) */
96
+ dbg.x = Math.max(Math.min(dbg.x, cols - 1), 0)
97
+ dbg.y = Math.max(Math.min(dbg.y, rows - 1), 0)
98
+ if (dbg.x > 0 && bufDst.getLine(bufDst.baseY + dbg.y)?.getCell(dbg.x)?.getWidth() === 0)
99
+ dbg.x--
100
+ const { x, y } = dbg
101
+ const cellSrc = bufSrc.getLine(bufSrc.baseY + y)?.getCell(x)
102
+ const cellDst = bufDst.getLine(bufDst.baseY + y)?.getCell(x)
103
+ const w = Math.max(cellDst?.getWidth() ?? 1, 1)
104
+
105
+ /* draw the debug cursor as a 3x3 frame (with rounded corners) around the observed cell */
106
+ const border = "\x1b[0;38;2;204;51;51m"
107
+ const plain = "\x1b[0m"
108
+ const frame = [ "╭" + "─".repeat(w) + "╮", "│" + " ".repeat(w) + "│", "╰" + "─".repeat(w) + "╯" ]
109
+ out += border
110
+ for (let r = 0; r < 3; r++) {
111
+ const fy = y - 1 + r
112
+ if (fy < 0 || fy >= rows)
113
+ continue
114
+ for (let c = 0; c < w + 2; c++) {
115
+ const fx = x - 1 + c
116
+ if (fx < 0 || fx >= cols || (r === 1 && c > 0 && c <= w))
117
+ continue
118
+ out += `\x1b[${fy + 1};${fx + 1}H` + frame[r][c]
119
+ }
120
+ dbg.covered.add(fy)
121
+ }
122
+
123
+ /* determine the info box lines (as content and its display width) */
124
+ const W = 36
125
+ const chars = cellDst?.getChars() ?? ""
126
+ const pos = `cell: ${x + 1},${y + 1}`
127
+ const lines: [ string, number ][] = []
128
+ if (chars === "")
129
+ lines.push([ `${pos} (empty)`, pos.length + 8 ])
130
+ else {
131
+ const cp = "U+" + (chars.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")
132
+ lines.push([ `${pos} ${cp} "${chars}"`, pos.length + cp.length + w + 4 ])
133
+ }
134
+ for (const [ label, cell, side ] of [ [ "source", cellSrc, "src" ], [ "target", cellDst, "dst" ] ] as const) {
135
+ for (const kind of [ "fg", "bg" ] as const) {
136
+ const color = cellColor(cell, kind)
137
+ const index = /^ansi (\d+)$/.exec(color.name)
138
+ const hint = color.name === "default" ? dbg.hints[side + kind] :
139
+ index !== null ? `= ${dbg.ansi[parseInt(index[1], 10)]}` : ""
140
+ const name = (hint !== "" ? `${color.name} ${hint}` : color.name).substring(0, W - 15)
141
+ const swatch = `\x1b[0;${color.sgr.join(";")}m${kind === "fg" ? "███" : " "}\x1b[0m`
142
+ lines.push([ `${label} ${kind}: ${swatch} ${name}`, 15 + name.length ])
143
+ }
144
+ }
145
+
146
+ /* draw the info box in the top-right corner
147
+ (or in the top-left corner, if the debug cursor is in the upper-right quadrant) */
148
+ const boxW = W + 4
149
+ const boxH = lines.length + 2
150
+ if (cols >= boxW && rows >= boxH) {
151
+ const bx = (y < rows / 2 && x >= cols / 2) ? 0 : cols - boxW
152
+ const by = 0
153
+ const title = "ANSI Quantone Debug"
154
+ const left = Math.floor((boxW - 2 - (title.length + 2)) / 2)
155
+ const right = boxW - 2 - (title.length + 2) - left
156
+ out += `${border}\x1b[${by + 1};${bx + 1}H╭${"─".repeat(left)}\x1b[1;7m ${title} ${border}${"─".repeat(right)}╮`
157
+ for (let i = 0; i < lines.length; i++)
158
+ out += `\x1b[${by + i + 2};${bx + 1}H${border}│${plain} ${lines[i][0]}${" ".repeat(W - lines[i][1])} ${border}│`
159
+ out += `\x1b[${by + boxH};${bx + 1}H╰${"─".repeat(boxW - 2)}╯`
160
+ for (let r = by; r < by + boxH; r++)
161
+ dbg.covered.add(r)
162
+ }
163
+ }
164
+
165
+ /* enable the mouse click reporting (in SGR encoding) while the debug overlay is displayed
166
+ (again on each rendering, as the command could have changed it), and afterwards
167
+ restore the mouse modes of the command (first all reset, then all set modes) */
168
+ if (dbg.active) {
169
+ out += "\x1b[?1000h\x1b[?1006h"
170
+ dbg.mouseOn = true
171
+ }
172
+ else if (dbg.mouseOn) {
173
+ for (const state of [ false, true ])
174
+ for (const mode of mouseModes)
175
+ if ((dbg.mouse.get(mode) ?? false) === state)
176
+ out += `\x1b[?${mode}${state ? "h" : "l"}`
177
+ dbg.mouseOn = false
178
+ }
179
+ out += "\x1b[0m" + (modes.insertMode ? "\x1b[4h" : "") + "\x1b8\x1b[?2026l"
180
+ dbg.output.write(out)
181
+ }
182
+
183
+ /* feed the source and target output into their emulated screens
184
+ and re-render the debug overlay once both screens parsed all output */
185
+ export const debugFeed = (dbg: Debug, source: Buffer, target: Buffer): void => {
186
+ if (dbg.covered.size > 0)
187
+ dbg.full = true
188
+ for (const [ screen, data ] of [ [ dbg.src, source ], [ dbg.dst, target ] ] as const) {
189
+ if (data.length === 0)
190
+ continue
191
+ dbg.pending++
192
+ screen.write(data, () => {
193
+ if (--dbg.pending === 0 && (dbg.active || dbg.covered.size > 0))
194
+ debugRender(dbg)
195
+ })
196
+ }
197
+ }
198
+
199
+ /* decode the key at an input position, in its legacy encoding or in the xterm
200
+ "modifyOtherKeys" or kitty keyboard protocol encoding (which applications like
201
+ "lazygit" enable), into its name ("C-a", "a", "d", "A"-"D" for the cursor keys,
202
+ "mod" for a sole modifier key, "click" for a left mouse button press at screen
203
+ position x/y, "mouse" for any other mouse event, or "" for any other key),
204
+ its length, and whether it is a key release event */
205
+ const decodeKey = (data: Buffer, i: number): { key: string, len: number, release: boolean, x?: number, y?: number } => {
206
+ if (data[i] !== 0x1B)
207
+ return { key: data[i] === 0x01 ? "C-a" : data[i] === 0x61 ? "a" : data[i] === 0x64 ? "d" : "", len: 1, release: false }
208
+ const s = data.subarray(i, i + 32).toString("latin1")
209
+ const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/.exec(s)
210
+ if (mouse !== null) {
211
+ /* SGR mouse event (left button press: button 0, with any modifiers, without motion) */
212
+ const click = (parseInt(mouse[1], 10) & ~(4 | 8 | 16)) === 0 && mouse[4] === "M"
213
+ const x = parseInt(mouse[2], 10) - 1
214
+ const y = parseInt(mouse[3], 10) - 1
215
+ return { key: click ? "click" : "mouse", len: mouse[0].length, release: false, x, y }
216
+ }
217
+ const cursor = /^\x1b(?:\[(?:1;\d+(?::(\d+))?)?|O)([A-D])/.exec(s)
218
+ if (cursor !== null)
219
+ return { key: cursor[2], len: cursor[0].length, release: cursor[1] === "3" }
220
+ const kitty = /^\x1b\[(\d+)(?::[\d:]*)?(?:;(\d+)(?::(\d+))?)?(?:;[\d:]*)?u/.exec(s)
221
+ const xterm = /^\x1b\[27;(\d+);(\d+)~/.exec(s)
222
+ const m = kitty ?? xterm
223
+ if (m !== null) {
224
+ /* key code and modifiers (ignoring the Caps Lock and Num Lock states) */
225
+ const code = parseInt(kitty !== null ? m[1] : m[2], 10)
226
+ const mods = (parseInt((kitty !== null ? m[2] : m[1]) ?? "1", 10) - 1) & ~(64 | 128)
227
+ let key = ""
228
+ if (code >= 57441 && code <= 57452) key = "mod"
229
+ else if (code === 97 && mods === 4) key = "C-a"
230
+ else if (code === 97 && mods === 0) key = "a"
231
+ else if (code === 100 && mods === 0) key = "d"
232
+ return { key, len: m[0].length, release: kitty !== null && m[3] === "3" }
233
+ }
234
+ const other = /^\x1b(?:\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|O.)/.exec(s)
235
+ return { key: "", len: other !== null ? other[0].length : 1, release: false }
236
+ }
237
+
238
+ /* handle the user input in debug mode: "CTRL+a d" toggles the debug overlay, "CTRL+a a"
239
+ and "CTRL+a CTRL+a" send a literal CTRL+a, and while the debug overlay is displayed,
240
+ the cursor keys and left mouse clicks move the debug cursor and all other input is discarded */
241
+ export const debugInput = (dbg: Debug, data: Buffer, forward: (data: Buffer) => void): void => {
242
+ let i = 0
243
+ while (i < data.length) {
244
+ if (dbg.prefix === null && !dbg.active && data[i] !== 0x01 && data[i] !== 0x1B) {
245
+ /* pass through all plain input up to the next potential prefix key */
246
+ let end = i
247
+ while (end < data.length && data[end] !== 0x01 && data[end] !== 0x1B)
248
+ end++
249
+ forward(data.subarray(i, end))
250
+ i = end
251
+ continue
252
+ }
253
+ const { key, len, release, x, y } = decodeKey(data, i)
254
+ const bytes = data.subarray(i, i + len)
255
+ i += len
256
+ if (release || key === "mod" || key === "mouse") {
257
+ /* key release, sole modifier key, or other mouse event: ignore it during the debug mode handling */
258
+ if (dbg.prefix === null && !dbg.active)
259
+ forward(bytes)
260
+ }
261
+ else if (dbg.prefix !== null) {
262
+ /* key after the prefix key */
263
+ if (key === "d") {
264
+ dbg.active = !dbg.active
265
+ if (dbg.active) {
266
+ dbg.x = Math.floor(dbg.dst.cols / 2)
267
+ dbg.y = Math.floor(dbg.dst.rows / 2)
268
+ }
269
+ debugRender(dbg)
270
+ }
271
+ else if ((key === "C-a" || key === "a") && !dbg.active)
272
+ forward(dbg.prefix)
273
+ dbg.prefix = null
274
+ }
275
+ else if (key === "C-a") {
276
+ /* prefix key (kept in its original encoding) */
277
+ dbg.prefix = Buffer.from(bytes)
278
+ }
279
+ else if (dbg.active && key === "click" && x !== undefined && y !== undefined) {
280
+ /* left mouse click positions the debug cursor */
281
+ dbg.x = x
282
+ dbg.y = y
283
+ debugRender(dbg)
284
+ }
285
+ else if (dbg.active) {
286
+ /* cursor keys move the debug cursor */
287
+ const buffer = dbg.dst.buffer.active
288
+ const width = buffer.getLine(buffer.baseY + dbg.y)?.getCell(dbg.x)?.getWidth() ?? 1
289
+ if (key === "A") dbg.y = Math.max(dbg.y - 1, 0)
290
+ else if (key === "B") dbg.y = Math.min(dbg.y + 1, dbg.dst.rows - 1)
291
+ else if (key === "C") dbg.x = Math.min(dbg.x + Math.max(width, 1), dbg.dst.cols - 1)
292
+ else if (key === "D") dbg.x = Math.max(dbg.x - 1, 0)
293
+ if ([ "A", "B", "C", "D" ].includes(key))
294
+ debugRender(dbg)
295
+ }
296
+ else
297
+ forward(bytes)
298
+ }
299
+ }
300
+
@@ -0,0 +1,77 @@
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
+ /* ==== color mapping rules ==== */
8
+
9
+ /* an input color: the terminal default color, an ANSI color index 0-255, or an RGB/truecolor value */
10
+ export type InputColor =
11
+ | { type: "default" }
12
+ | { type: "index", index: number }
13
+ | { type: "rgb", rgb: number }
14
+
15
+ /* a color of a mapping rule (ranges and classes on the source side only) */
16
+ export type ColorSpec =
17
+ | InputColor
18
+ | { type: "wildcard" }
19
+ | { type: "range", from: number, to: number }
20
+ | { type: "class", family: string | null, tone: string | null }
21
+
22
+ /* a color mapping rule "<fg>/<bg> : <fg>/<bg>" */
23
+ export type ColorMapping = { fromFg: ColorSpec, fromBg: ColorSpec, toFg: ColorSpec, toBg: ColorSpec }
24
+
25
+ /* the lower-case ANSI color names onto their index (as in Quantone) */
26
+ const colorNames = new Map<string, number>([ [ "gray", 8 ], [ "grey", 8 ] ])
27
+ const baseNames = [ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white" ]
28
+ for (let i = 0; i < baseNames.length; i++) {
29
+ colorNames.set(baseNames[i], i)
30
+ colorNames.set(`bright${baseNames[i]}`, i + 8)
31
+ colorNames.set(`${baseNames[i]}bright`, i + 8)
32
+ }
33
+
34
+ /* parse a color of a mapping rule */
35
+ const parseColorSpec = (spec: string, target: boolean): ColorSpec => {
36
+ if (spec === "*")
37
+ return { type: "wildcard" }
38
+ if (spec === "default")
39
+ return { type: "default" }
40
+ const hex = spec.match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/)
41
+ if (hex !== null) {
42
+ let n = parseInt(hex[1], 16)
43
+ if (hex[1].length === 3)
44
+ n = ((n & 0xF00) * 0x1100) | ((n & 0x0F0) * 0x110) | ((n & 0x00F) * 0x11)
45
+ return { type: "rgb", rgb: n }
46
+ }
47
+ if (/^\d{1,3}$/.test(spec) && parseInt(spec, 10) <= 255)
48
+ return { type: "index", index: parseInt(spec, 10) }
49
+ const index = colorNames.get(spec.toLowerCase())
50
+ if (index !== undefined)
51
+ return { type: "index", index }
52
+ const range = spec.match(/^(\d{1,3})\.\.(\d{1,3})$/)
53
+ if (!target && range !== null) {
54
+ const from = parseInt(range[1], 10)
55
+ const to = parseInt(range[2], 10)
56
+ if (from <= to && to <= 255)
57
+ return { type: "range", from, to }
58
+ }
59
+ const cls = spec.match(/^@(?:(warm|cool|grey|gray)(?:\.(dark|mid|light))?|(dark|mid|light))$/)
60
+ if (!target && cls !== null)
61
+ return { type: "class", family: cls[1] === "gray" ? "grey" : (cls[1] ?? null), tone: cls[2] ?? cls[3] ?? null }
62
+ throw new Error(`invalid ${target ? "target" : "source"} color "${spec}"`)
63
+ }
64
+
65
+ /* parse a color mapping rule "<fg>/<bg> : <fg>/<bg>" */
66
+ export const parseMapping = (text: string): ColorMapping => {
67
+ const m = text.match(/^\s*([^\s/:]+)\/([^\s/:]+)\s*:\s*([^\s/:]+)\/([^\s/:]+)\s*$/)
68
+ if (m === null)
69
+ throw new Error("expected \"<fg>/<bg> : <fg>/<bg>\"")
70
+ return {
71
+ fromFg: parseColorSpec(m[1], false),
72
+ fromBg: parseColorSpec(m[2], false),
73
+ toFg: parseColorSpec(m[3], true),
74
+ toBg: parseColorSpec(m[4], true)
75
+ }
76
+ }
77
+