@caupulican/pi-tui 0.78.2
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/README.md +779 -0
- package/dist/autocomplete.d.ts +54 -0
- package/dist/autocomplete.d.ts.map +1 -0
- package/dist/autocomplete.js +632 -0
- package/dist/autocomplete.js.map +1 -0
- package/dist/components/box.d.ts +22 -0
- package/dist/components/box.d.ts.map +1 -0
- package/dist/components/box.js +104 -0
- package/dist/components/box.js.map +1 -0
- package/dist/components/cancellable-loader.d.ts +22 -0
- package/dist/components/cancellable-loader.d.ts.map +1 -0
- package/dist/components/cancellable-loader.js +35 -0
- package/dist/components/cancellable-loader.js.map +1 -0
- package/dist/components/editor.d.ts +249 -0
- package/dist/components/editor.d.ts.map +1 -0
- package/dist/components/editor.js +1857 -0
- package/dist/components/editor.js.map +1 -0
- package/dist/components/image.d.ts +28 -0
- package/dist/components/image.d.ts.map +1 -0
- package/dist/components/image.js +89 -0
- package/dist/components/image.js.map +1 -0
- package/dist/components/input.d.ts +37 -0
- package/dist/components/input.d.ts.map +1 -0
- package/dist/components/input.js +378 -0
- package/dist/components/input.js.map +1 -0
- package/dist/components/loader.d.ts +31 -0
- package/dist/components/loader.d.ts.map +1 -0
- package/dist/components/loader.js +69 -0
- package/dist/components/loader.js.map +1 -0
- package/dist/components/markdown.d.ts +96 -0
- package/dist/components/markdown.d.ts.map +1 -0
- package/dist/components/markdown.js +644 -0
- package/dist/components/markdown.js.map +1 -0
- package/dist/components/select-list.d.ts +50 -0
- package/dist/components/select-list.d.ts.map +1 -0
- package/dist/components/select-list.js +159 -0
- package/dist/components/select-list.js.map +1 -0
- package/dist/components/settings-list.d.ts +50 -0
- package/dist/components/settings-list.d.ts.map +1 -0
- package/dist/components/settings-list.js +185 -0
- package/dist/components/settings-list.js.map +1 -0
- package/dist/components/spacer.d.ts +12 -0
- package/dist/components/spacer.d.ts.map +1 -0
- package/dist/components/spacer.js +23 -0
- package/dist/components/spacer.js.map +1 -0
- package/dist/components/text.d.ts +19 -0
- package/dist/components/text.d.ts.map +1 -0
- package/dist/components/text.js +89 -0
- package/dist/components/text.js.map +1 -0
- package/dist/components/truncated-text.d.ts +13 -0
- package/dist/components/truncated-text.d.ts.map +1 -0
- package/dist/components/truncated-text.js +51 -0
- package/dist/components/truncated-text.js.map +1 -0
- package/dist/editor-component.d.ts +39 -0
- package/dist/editor-component.d.ts.map +1 -0
- package/dist/editor-component.js +2 -0
- package/dist/editor-component.js.map +1 -0
- package/dist/fuzzy.d.ts +16 -0
- package/dist/fuzzy.d.ts.map +1 -0
- package/dist/fuzzy.js +110 -0
- package/dist/fuzzy.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/keybindings.d.ts +193 -0
- package/dist/keybindings.d.ts.map +1 -0
- package/dist/keybindings.js +174 -0
- package/dist/keybindings.js.map +1 -0
- package/dist/keys.d.ts +184 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +1173 -0
- package/dist/keys.js.map +1 -0
- package/dist/kill-ring.d.ts +28 -0
- package/dist/kill-ring.d.ts.map +1 -0
- package/dist/kill-ring.js +44 -0
- package/dist/kill-ring.js.map +1 -0
- package/dist/native-modifiers.d.ts +3 -0
- package/dist/native-modifiers.d.ts.map +1 -0
- package/dist/native-modifiers.js +53 -0
- package/dist/native-modifiers.js.map +1 -0
- package/dist/stdin-buffer.d.ts +50 -0
- package/dist/stdin-buffer.d.ts.map +1 -0
- package/dist/stdin-buffer.js +361 -0
- package/dist/stdin-buffer.js.map +1 -0
- package/dist/terminal-image.d.ts +90 -0
- package/dist/terminal-image.d.ts.map +1 -0
- package/dist/terminal-image.js +366 -0
- package/dist/terminal-image.js.map +1 -0
- package/dist/terminal.d.ts +113 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +472 -0
- package/dist/terminal.js.map +1 -0
- package/dist/tui.d.ts +227 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +1077 -0
- package/dist/tui.js.map +1 -0
- package/dist/undo-stack.d.ts +17 -0
- package/dist/undo-stack.d.ts.map +1 -0
- package/dist/undo-stack.js +25 -0
- package/dist/undo-stack.js.map +1 -0
- package/dist/utils.d.ts +84 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +1029 -0
- package/dist/utils.js.map +1 -0
- package/dist/word-navigation.d.ts +25 -0
- package/dist/word-navigation.d.ts.map +1 -0
- package/dist/word-navigation.js +96 -0
- package/dist/word-navigation.js.map +1 -0
- package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
- package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
- package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
- package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
- package/package.json +47 -0
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
let cachedCapabilities = null;
|
|
3
|
+
// Default cell dimensions - updated by TUI when terminal responds to query
|
|
4
|
+
let cellDimensions = { widthPx: 9, heightPx: 18 };
|
|
5
|
+
export function getCellDimensions() {
|
|
6
|
+
return cellDimensions;
|
|
7
|
+
}
|
|
8
|
+
export function setCellDimensions(dims) {
|
|
9
|
+
cellDimensions = dims;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Checks whether the attached tmux client forwards OSC 8 hyperlinks to the
|
|
13
|
+
* outer terminal. tmux only re-emits them when its `client_termfeatures` lists
|
|
14
|
+
* `hyperlinks`, and strips them otherwise. On any error fallbacks `false`.
|
|
15
|
+
*/
|
|
16
|
+
function probeTmuxHyperlinks() {
|
|
17
|
+
try {
|
|
18
|
+
const termfeatures = execSync("tmux display-message -p '#{client_termfeatures}'", {
|
|
19
|
+
encoding: "utf8",
|
|
20
|
+
timeout: 250,
|
|
21
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
22
|
+
});
|
|
23
|
+
return termfeatures
|
|
24
|
+
.split(",")
|
|
25
|
+
.map((feature) => feature.trim())
|
|
26
|
+
.includes("hyperlinks");
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function detectCapabilities(tmuxForwardsHyperlink = probeTmuxHyperlinks) {
|
|
33
|
+
const termProgram = process.env.TERM_PROGRAM?.toLowerCase() || "";
|
|
34
|
+
const terminalEmulator = process.env.TERMINAL_EMULATOR?.toLowerCase() || "";
|
|
35
|
+
const term = process.env.TERM?.toLowerCase() || "";
|
|
36
|
+
const colorTerm = process.env.COLORTERM?.toLowerCase() || "";
|
|
37
|
+
const hasTrueColorHint = colorTerm === "truecolor" || colorTerm === "24bit";
|
|
38
|
+
// Emit OSC 8 hyperlinks only when tmux confirms it forwards.
|
|
39
|
+
// Image protocols are unreliable under tmux, so leave `images: null`.
|
|
40
|
+
if (process.env.TMUX || term.startsWith("tmux")) {
|
|
41
|
+
return { images: null, trueColor: hasTrueColorHint, hyperlinks: tmuxForwardsHyperlink() };
|
|
42
|
+
}
|
|
43
|
+
// screen does not forward OSC 8 hyperlinks, so keep them off there.
|
|
44
|
+
if (term.startsWith("screen")) {
|
|
45
|
+
return { images: null, trueColor: hasTrueColorHint, hyperlinks: false };
|
|
46
|
+
}
|
|
47
|
+
if (process.env.KITTY_WINDOW_ID || termProgram === "kitty") {
|
|
48
|
+
return { images: "kitty", trueColor: true, hyperlinks: true };
|
|
49
|
+
}
|
|
50
|
+
if (termProgram === "ghostty" || term.includes("ghostty") || process.env.GHOSTTY_RESOURCES_DIR) {
|
|
51
|
+
return { images: "kitty", trueColor: true, hyperlinks: true };
|
|
52
|
+
}
|
|
53
|
+
if (process.env.WEZTERM_PANE || termProgram === "wezterm") {
|
|
54
|
+
return { images: "kitty", trueColor: true, hyperlinks: true };
|
|
55
|
+
}
|
|
56
|
+
if (process.env.ITERM_SESSION_ID || termProgram === "iterm.app") {
|
|
57
|
+
return { images: "iterm2", trueColor: true, hyperlinks: true };
|
|
58
|
+
}
|
|
59
|
+
if (process.env.WT_SESSION) {
|
|
60
|
+
return { images: null, trueColor: true, hyperlinks: true };
|
|
61
|
+
}
|
|
62
|
+
if (termProgram === "vscode") {
|
|
63
|
+
return { images: null, trueColor: true, hyperlinks: true };
|
|
64
|
+
}
|
|
65
|
+
if (termProgram === "alacritty") {
|
|
66
|
+
return { images: null, trueColor: true, hyperlinks: true };
|
|
67
|
+
}
|
|
68
|
+
if (terminalEmulator === "jetbrains-jediterm") {
|
|
69
|
+
return { images: null, trueColor: true, hyperlinks: false };
|
|
70
|
+
}
|
|
71
|
+
// Unknown terminal: be conservative. OSC 8 is rendered invisibly as "just
|
|
72
|
+
// text" on terminals that swallow it, which means the URL disappears from
|
|
73
|
+
// the rendered output. Default to the legacy `text (url)` behavior unless we
|
|
74
|
+
// have positively identified a hyperlink-capable terminal above.
|
|
75
|
+
return { images: null, trueColor: hasTrueColorHint, hyperlinks: false };
|
|
76
|
+
}
|
|
77
|
+
export function getCapabilities() {
|
|
78
|
+
if (!cachedCapabilities) {
|
|
79
|
+
cachedCapabilities = detectCapabilities();
|
|
80
|
+
}
|
|
81
|
+
return cachedCapabilities;
|
|
82
|
+
}
|
|
83
|
+
export function resetCapabilitiesCache() {
|
|
84
|
+
cachedCapabilities = null;
|
|
85
|
+
}
|
|
86
|
+
/** Override the cached capabilities. Useful in tests to exercise both code paths. */
|
|
87
|
+
export function setCapabilities(caps) {
|
|
88
|
+
cachedCapabilities = caps;
|
|
89
|
+
}
|
|
90
|
+
const KITTY_PREFIX = "\x1b_G";
|
|
91
|
+
const ITERM2_PREFIX = "\x1b]1337;File=";
|
|
92
|
+
export function isImageLine(line) {
|
|
93
|
+
// Fast path: sequence at line start (single-row images)
|
|
94
|
+
if (line.startsWith(KITTY_PREFIX) || line.startsWith(ITERM2_PREFIX)) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
// Slow path: sequence elsewhere (multi-row images have cursor-up prefix)
|
|
98
|
+
return line.includes(KITTY_PREFIX) || line.includes(ITERM2_PREFIX);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Generate a random image ID for Kitty graphics protocol.
|
|
102
|
+
* Uses random IDs to avoid collisions between different module instances
|
|
103
|
+
* (e.g., main app vs extensions).
|
|
104
|
+
*/
|
|
105
|
+
export function allocateImageId() {
|
|
106
|
+
// Use random ID in range [1, 0xffffffff] to avoid collisions
|
|
107
|
+
return Math.floor(Math.random() * 0xfffffffe) + 1;
|
|
108
|
+
}
|
|
109
|
+
export function encodeKitty(base64Data, options = {}) {
|
|
110
|
+
const CHUNK_SIZE = 4096;
|
|
111
|
+
const params = ["a=T", "f=100", "q=2"];
|
|
112
|
+
if (options.moveCursor === false)
|
|
113
|
+
params.push("C=1");
|
|
114
|
+
if (options.columns)
|
|
115
|
+
params.push(`c=${options.columns}`);
|
|
116
|
+
if (options.rows)
|
|
117
|
+
params.push(`r=${options.rows}`);
|
|
118
|
+
if (options.imageId)
|
|
119
|
+
params.push(`i=${options.imageId}`);
|
|
120
|
+
if (base64Data.length <= CHUNK_SIZE) {
|
|
121
|
+
return `\x1b_G${params.join(",")};${base64Data}\x1b\\`;
|
|
122
|
+
}
|
|
123
|
+
const chunks = [];
|
|
124
|
+
let offset = 0;
|
|
125
|
+
let isFirst = true;
|
|
126
|
+
while (offset < base64Data.length) {
|
|
127
|
+
const chunk = base64Data.slice(offset, offset + CHUNK_SIZE);
|
|
128
|
+
const isLast = offset + CHUNK_SIZE >= base64Data.length;
|
|
129
|
+
if (isFirst) {
|
|
130
|
+
chunks.push(`\x1b_G${params.join(",")},m=1;${chunk}\x1b\\`);
|
|
131
|
+
isFirst = false;
|
|
132
|
+
}
|
|
133
|
+
else if (isLast) {
|
|
134
|
+
chunks.push(`\x1b_Gm=0;${chunk}\x1b\\`);
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
chunks.push(`\x1b_Gm=1;${chunk}\x1b\\`);
|
|
138
|
+
}
|
|
139
|
+
offset += CHUNK_SIZE;
|
|
140
|
+
}
|
|
141
|
+
return chunks.join("");
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Delete a Kitty graphics image by ID.
|
|
145
|
+
* Uses uppercase 'I' to also free the image data.
|
|
146
|
+
*/
|
|
147
|
+
export function deleteKittyImage(imageId) {
|
|
148
|
+
return `\x1b_Ga=d,d=I,i=${imageId},q=2\x1b\\`;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Delete all visible Kitty graphics images.
|
|
152
|
+
* Uses uppercase 'A' to also free the image data.
|
|
153
|
+
*/
|
|
154
|
+
export function deleteAllKittyImages() {
|
|
155
|
+
return "\x1b_Ga=d,d=A,q=2\x1b\\";
|
|
156
|
+
}
|
|
157
|
+
export function encodeITerm2(base64Data, options = {}) {
|
|
158
|
+
const params = [`inline=${options.inline !== false ? 1 : 0}`];
|
|
159
|
+
if (options.width !== undefined)
|
|
160
|
+
params.push(`width=${options.width}`);
|
|
161
|
+
if (options.height !== undefined)
|
|
162
|
+
params.push(`height=${options.height}`);
|
|
163
|
+
if (options.name) {
|
|
164
|
+
const nameBase64 = Buffer.from(options.name).toString("base64");
|
|
165
|
+
params.push(`name=${nameBase64}`);
|
|
166
|
+
}
|
|
167
|
+
if (options.preserveAspectRatio === false) {
|
|
168
|
+
params.push("preserveAspectRatio=0");
|
|
169
|
+
}
|
|
170
|
+
return `\x1b]1337;File=${params.join(";")}:${base64Data}\x07`;
|
|
171
|
+
}
|
|
172
|
+
export function calculateImageCellSize(imageDimensions, maxWidthCells, maxHeightCells, cellDimensions = { widthPx: 9, heightPx: 18 }) {
|
|
173
|
+
const maxWidth = Math.max(1, Math.floor(maxWidthCells));
|
|
174
|
+
const maxHeight = maxHeightCells === undefined ? undefined : Math.max(1, Math.floor(maxHeightCells));
|
|
175
|
+
const imageWidth = Math.max(1, imageDimensions.widthPx);
|
|
176
|
+
const imageHeight = Math.max(1, imageDimensions.heightPx);
|
|
177
|
+
const widthScale = (maxWidth * cellDimensions.widthPx) / imageWidth;
|
|
178
|
+
const heightScale = maxHeight === undefined ? widthScale : (maxHeight * cellDimensions.heightPx) / imageHeight;
|
|
179
|
+
const scale = Math.min(widthScale, heightScale);
|
|
180
|
+
const scaledWidthPx = imageWidth * scale;
|
|
181
|
+
const scaledHeightPx = imageHeight * scale;
|
|
182
|
+
const columns = Math.ceil(scaledWidthPx / cellDimensions.widthPx);
|
|
183
|
+
const rows = Math.ceil(scaledHeightPx / cellDimensions.heightPx);
|
|
184
|
+
return {
|
|
185
|
+
columns: Math.max(1, Math.min(maxWidth, columns)),
|
|
186
|
+
rows: Math.max(1, maxHeight === undefined ? rows : Math.min(maxHeight, rows)),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
export function calculateImageRows(imageDimensions, targetWidthCells, cellDimensions = { widthPx: 9, heightPx: 18 }) {
|
|
190
|
+
return calculateImageCellSize(imageDimensions, targetWidthCells, undefined, cellDimensions).rows;
|
|
191
|
+
}
|
|
192
|
+
export function getPngDimensions(base64Data) {
|
|
193
|
+
try {
|
|
194
|
+
const buffer = Buffer.from(base64Data, "base64");
|
|
195
|
+
if (buffer.length < 24) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
if (buffer[0] !== 0x89 || buffer[1] !== 0x50 || buffer[2] !== 0x4e || buffer[3] !== 0x47) {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
const width = buffer.readUInt32BE(16);
|
|
202
|
+
const height = buffer.readUInt32BE(20);
|
|
203
|
+
return { widthPx: width, heightPx: height };
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
export function getJpegDimensions(base64Data) {
|
|
210
|
+
try {
|
|
211
|
+
const buffer = Buffer.from(base64Data, "base64");
|
|
212
|
+
if (buffer.length < 2) {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
if (buffer[0] !== 0xff || buffer[1] !== 0xd8) {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
let offset = 2;
|
|
219
|
+
while (offset < buffer.length - 9) {
|
|
220
|
+
if (buffer[offset] !== 0xff) {
|
|
221
|
+
offset++;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const marker = buffer[offset + 1];
|
|
225
|
+
if (marker >= 0xc0 && marker <= 0xc2) {
|
|
226
|
+
const height = buffer.readUInt16BE(offset + 5);
|
|
227
|
+
const width = buffer.readUInt16BE(offset + 7);
|
|
228
|
+
return { widthPx: width, heightPx: height };
|
|
229
|
+
}
|
|
230
|
+
if (offset + 3 >= buffer.length) {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
const length = buffer.readUInt16BE(offset + 2);
|
|
234
|
+
if (length < 2) {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
offset += 2 + length;
|
|
238
|
+
}
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
export function getGifDimensions(base64Data) {
|
|
246
|
+
try {
|
|
247
|
+
const buffer = Buffer.from(base64Data, "base64");
|
|
248
|
+
if (buffer.length < 10) {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
const sig = buffer.slice(0, 6).toString("ascii");
|
|
252
|
+
if (sig !== "GIF87a" && sig !== "GIF89a") {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
const width = buffer.readUInt16LE(6);
|
|
256
|
+
const height = buffer.readUInt16LE(8);
|
|
257
|
+
return { widthPx: width, heightPx: height };
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
export function getWebpDimensions(base64Data) {
|
|
264
|
+
try {
|
|
265
|
+
const buffer = Buffer.from(base64Data, "base64");
|
|
266
|
+
if (buffer.length < 30) {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
const riff = buffer.slice(0, 4).toString("ascii");
|
|
270
|
+
const webp = buffer.slice(8, 12).toString("ascii");
|
|
271
|
+
if (riff !== "RIFF" || webp !== "WEBP") {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
const chunk = buffer.slice(12, 16).toString("ascii");
|
|
275
|
+
if (chunk === "VP8 ") {
|
|
276
|
+
if (buffer.length < 30)
|
|
277
|
+
return null;
|
|
278
|
+
const width = buffer.readUInt16LE(26) & 0x3fff;
|
|
279
|
+
const height = buffer.readUInt16LE(28) & 0x3fff;
|
|
280
|
+
return { widthPx: width, heightPx: height };
|
|
281
|
+
}
|
|
282
|
+
else if (chunk === "VP8L") {
|
|
283
|
+
if (buffer.length < 25)
|
|
284
|
+
return null;
|
|
285
|
+
const bits = buffer.readUInt32LE(21);
|
|
286
|
+
const width = (bits & 0x3fff) + 1;
|
|
287
|
+
const height = ((bits >> 14) & 0x3fff) + 1;
|
|
288
|
+
return { widthPx: width, heightPx: height };
|
|
289
|
+
}
|
|
290
|
+
else if (chunk === "VP8X") {
|
|
291
|
+
if (buffer.length < 30)
|
|
292
|
+
return null;
|
|
293
|
+
const width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;
|
|
294
|
+
const height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;
|
|
295
|
+
return { widthPx: width, heightPx: height };
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
export function getImageDimensions(base64Data, mimeType) {
|
|
304
|
+
if (mimeType === "image/png") {
|
|
305
|
+
return getPngDimensions(base64Data);
|
|
306
|
+
}
|
|
307
|
+
if (mimeType === "image/jpeg") {
|
|
308
|
+
return getJpegDimensions(base64Data);
|
|
309
|
+
}
|
|
310
|
+
if (mimeType === "image/gif") {
|
|
311
|
+
return getGifDimensions(base64Data);
|
|
312
|
+
}
|
|
313
|
+
if (mimeType === "image/webp") {
|
|
314
|
+
return getWebpDimensions(base64Data);
|
|
315
|
+
}
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
export function renderImage(base64Data, imageDimensions, options = {}) {
|
|
319
|
+
const caps = getCapabilities();
|
|
320
|
+
if (!caps.images) {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
const maxWidth = options.maxWidthCells ?? 80;
|
|
324
|
+
const size = calculateImageCellSize(imageDimensions, maxWidth, options.maxHeightCells, getCellDimensions());
|
|
325
|
+
if (caps.images === "kitty") {
|
|
326
|
+
const sequence = encodeKitty(base64Data, {
|
|
327
|
+
columns: size.columns,
|
|
328
|
+
rows: size.rows,
|
|
329
|
+
imageId: options.imageId,
|
|
330
|
+
moveCursor: options.moveCursor,
|
|
331
|
+
});
|
|
332
|
+
return { sequence, rows: size.rows, imageId: options.imageId };
|
|
333
|
+
}
|
|
334
|
+
if (caps.images === "iterm2") {
|
|
335
|
+
const sequence = encodeITerm2(base64Data, {
|
|
336
|
+
width: size.columns,
|
|
337
|
+
height: "auto",
|
|
338
|
+
preserveAspectRatio: options.preserveAspectRatio ?? true,
|
|
339
|
+
});
|
|
340
|
+
return { sequence, rows: size.rows };
|
|
341
|
+
}
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Wrap text in an OSC 8 hyperlink sequence.
|
|
346
|
+
* The text is rendered as a clickable hyperlink in terminals that support OSC 8
|
|
347
|
+
* (Ghostty, Kitty, WezTerm, iTerm2, VSCode, and others).
|
|
348
|
+
* In terminals that do not support OSC 8, the escape sequences are ignored
|
|
349
|
+
* and only the plain text is displayed.
|
|
350
|
+
*
|
|
351
|
+
* @param text - The visible text to display
|
|
352
|
+
* @param url - The URL to link to
|
|
353
|
+
*/
|
|
354
|
+
export function hyperlink(text, url) {
|
|
355
|
+
return `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\`;
|
|
356
|
+
}
|
|
357
|
+
export function imageFallback(mimeType, dimensions, filename) {
|
|
358
|
+
const parts = [];
|
|
359
|
+
if (filename)
|
|
360
|
+
parts.push(filename);
|
|
361
|
+
parts.push(`[${mimeType}]`);
|
|
362
|
+
if (dimensions)
|
|
363
|
+
parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`);
|
|
364
|
+
return `[Image: ${parts.join(" ")}]`;
|
|
365
|
+
}
|
|
366
|
+
//# sourceMappingURL=terminal-image.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal-image.js","sourceRoot":"","sources":["../src/terminal-image.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AA8B9C,IAAI,kBAAkB,GAAgC,IAAI,CAAC;AAE3D,2EAA2E;AAC3E,IAAI,cAAc,GAAmB,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAElE,MAAM,UAAU,iBAAiB,GAAmB;IACnD,OAAO,cAAc,CAAC;AAAA,CACtB;AAED,MAAM,UAAU,iBAAiB,CAAC,IAAoB,EAAQ;IAC7D,cAAc,GAAG,IAAI,CAAC;AAAA,CACtB;AAED;;;;GAIG;AACH,SAAS,mBAAmB,GAAY;IACvC,IAAI,CAAC;QACJ,MAAM,YAAY,GAAG,QAAQ,CAAC,kDAAkD,EAAE;YACjF,QAAQ,EAAE,MAAM;YAChB,OAAO,EAAE,GAAG;YACZ,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC;SACnC,CAAC,CAAC;QACH,OAAO,YAAY;aACjB,KAAK,CAAC,GAAG,CAAC;aACV,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;aAChC,QAAQ,CAAC,YAAY,CAAC,CAAC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5B,IAAI,UAAU;QAAE,KAAK,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC3E,OAAO,WAAW,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AAAA,CACrC","sourcesContent":["import { execSync } from \"node:child_process\";\n\nexport type ImageProtocol = \"kitty\" | \"iterm2\" | null;\n\nexport interface TerminalCapabilities {\n\timages: ImageProtocol;\n\ttrueColor: boolean;\n\thyperlinks: boolean;\n}\n\nexport interface CellDimensions {\n\twidthPx: number;\n\theightPx: number;\n}\n\nexport interface ImageDimensions {\n\twidthPx: number;\n\theightPx: number;\n}\n\nexport interface ImageRenderOptions {\n\tmaxWidthCells?: number;\n\tmaxHeightCells?: number;\n\tpreserveAspectRatio?: boolean;\n\t/** Kitty image ID. If provided, reuses/replaces existing image with this ID. */\n\timageId?: number;\n\t/** Whether Kitty should apply its default cursor movement after placement. */\n\tmoveCursor?: boolean;\n}\n\nlet cachedCapabilities: TerminalCapabilities | null = null;\n\n// Default cell dimensions - updated by TUI when terminal responds to query\nlet cellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 };\n\nexport function getCellDimensions(): CellDimensions {\n\treturn cellDimensions;\n}\n\nexport function setCellDimensions(dims: CellDimensions): void {\n\tcellDimensions = dims;\n}\n\n/**\n * Checks whether the attached tmux client forwards OSC 8 hyperlinks to the\n * outer terminal. tmux only re-emits them when its `client_termfeatures` lists\n * `hyperlinks`, and strips them otherwise. On any error fallbacks `false`.\n */\nfunction probeTmuxHyperlinks(): boolean {\n\ttry {\n\t\tconst termfeatures = execSync(\"tmux display-message -p '#{client_termfeatures}'\", {\n\t\t\tencoding: \"utf8\",\n\t\t\ttimeout: 250,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\treturn termfeatures\n\t\t\t.split(\",\")\n\t\t\t.map((feature) => feature.trim())\n\t\t\t.includes(\"hyperlinks\");\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function detectCapabilities(tmuxForwardsHyperlink: () => boolean = probeTmuxHyperlinks): TerminalCapabilities {\n\tconst termProgram = process.env.TERM_PROGRAM?.toLowerCase() || \"\";\n\tconst terminalEmulator = process.env.TERMINAL_EMULATOR?.toLowerCase() || \"\";\n\tconst term = process.env.TERM?.toLowerCase() || \"\";\n\tconst colorTerm = process.env.COLORTERM?.toLowerCase() || \"\";\n\tconst hasTrueColorHint = colorTerm === \"truecolor\" || colorTerm === \"24bit\";\n\n\t// Emit OSC 8 hyperlinks only when tmux confirms it forwards.\n\t// Image protocols are unreliable under tmux, so leave `images: null`.\n\tif (process.env.TMUX || term.startsWith(\"tmux\")) {\n\t\treturn { images: null, trueColor: hasTrueColorHint, hyperlinks: tmuxForwardsHyperlink() };\n\t}\n\n\t// screen does not forward OSC 8 hyperlinks, so keep them off there.\n\tif (term.startsWith(\"screen\")) {\n\t\treturn { images: null, trueColor: hasTrueColorHint, hyperlinks: false };\n\t}\n\n\tif (process.env.KITTY_WINDOW_ID || termProgram === \"kitty\") {\n\t\treturn { images: \"kitty\", trueColor: true, hyperlinks: true };\n\t}\n\n\tif (termProgram === \"ghostty\" || term.includes(\"ghostty\") || process.env.GHOSTTY_RESOURCES_DIR) {\n\t\treturn { images: \"kitty\", trueColor: true, hyperlinks: true };\n\t}\n\n\tif (process.env.WEZTERM_PANE || termProgram === \"wezterm\") {\n\t\treturn { images: \"kitty\", trueColor: true, hyperlinks: true };\n\t}\n\n\tif (process.env.ITERM_SESSION_ID || termProgram === \"iterm.app\") {\n\t\treturn { images: \"iterm2\", trueColor: true, hyperlinks: true };\n\t}\n\n\tif (process.env.WT_SESSION) {\n\t\treturn { images: null, trueColor: true, hyperlinks: true };\n\t}\n\n\tif (termProgram === \"vscode\") {\n\t\treturn { images: null, trueColor: true, hyperlinks: true };\n\t}\n\n\tif (termProgram === \"alacritty\") {\n\t\treturn { images: null, trueColor: true, hyperlinks: true };\n\t}\n\n\tif (terminalEmulator === \"jetbrains-jediterm\") {\n\t\treturn { images: null, trueColor: true, hyperlinks: false };\n\t}\n\n\t// Unknown terminal: be conservative. OSC 8 is rendered invisibly as \"just\n\t// text\" on terminals that swallow it, which means the URL disappears from\n\t// the rendered output. Default to the legacy `text (url)` behavior unless we\n\t// have positively identified a hyperlink-capable terminal above.\n\treturn { images: null, trueColor: hasTrueColorHint, hyperlinks: false };\n}\n\nexport function getCapabilities(): TerminalCapabilities {\n\tif (!cachedCapabilities) {\n\t\tcachedCapabilities = detectCapabilities();\n\t}\n\treturn cachedCapabilities;\n}\n\nexport function resetCapabilitiesCache(): void {\n\tcachedCapabilities = null;\n}\n\n/** Override the cached capabilities. Useful in tests to exercise both code paths. */\nexport function setCapabilities(caps: TerminalCapabilities): void {\n\tcachedCapabilities = caps;\n}\n\nconst KITTY_PREFIX = \"\\x1b_G\";\nconst ITERM2_PREFIX = \"\\x1b]1337;File=\";\n\nexport function isImageLine(line: string): boolean {\n\t// Fast path: sequence at line start (single-row images)\n\tif (line.startsWith(KITTY_PREFIX) || line.startsWith(ITERM2_PREFIX)) {\n\t\treturn true;\n\t}\n\t// Slow path: sequence elsewhere (multi-row images have cursor-up prefix)\n\treturn line.includes(KITTY_PREFIX) || line.includes(ITERM2_PREFIX);\n}\n\n/**\n * Generate a random image ID for Kitty graphics protocol.\n * Uses random IDs to avoid collisions between different module instances\n * (e.g., main app vs extensions).\n */\nexport function allocateImageId(): number {\n\t// Use random ID in range [1, 0xffffffff] to avoid collisions\n\treturn Math.floor(Math.random() * 0xfffffffe) + 1;\n}\n\nexport function encodeKitty(\n\tbase64Data: string,\n\toptions: {\n\t\tcolumns?: number;\n\t\trows?: number;\n\t\timageId?: number;\n\t\t/** Whether Kitty should apply its default cursor movement after placement. Default: true. */\n\t\tmoveCursor?: boolean;\n\t} = {},\n): string {\n\tconst CHUNK_SIZE = 4096;\n\n\tconst params: string[] = [\"a=T\", \"f=100\", \"q=2\"];\n\n\tif (options.moveCursor === false) params.push(\"C=1\");\n\tif (options.columns) params.push(`c=${options.columns}`);\n\tif (options.rows) params.push(`r=${options.rows}`);\n\tif (options.imageId) params.push(`i=${options.imageId}`);\n\n\tif (base64Data.length <= CHUNK_SIZE) {\n\t\treturn `\\x1b_G${params.join(\",\")};${base64Data}\\x1b\\\\`;\n\t}\n\n\tconst chunks: string[] = [];\n\tlet offset = 0;\n\tlet isFirst = true;\n\n\twhile (offset < base64Data.length) {\n\t\tconst chunk = base64Data.slice(offset, offset + CHUNK_SIZE);\n\t\tconst isLast = offset + CHUNK_SIZE >= base64Data.length;\n\n\t\tif (isFirst) {\n\t\t\tchunks.push(`\\x1b_G${params.join(\",\")},m=1;${chunk}\\x1b\\\\`);\n\t\t\tisFirst = false;\n\t\t} else if (isLast) {\n\t\t\tchunks.push(`\\x1b_Gm=0;${chunk}\\x1b\\\\`);\n\t\t} else {\n\t\t\tchunks.push(`\\x1b_Gm=1;${chunk}\\x1b\\\\`);\n\t\t}\n\n\t\toffset += CHUNK_SIZE;\n\t}\n\n\treturn chunks.join(\"\");\n}\n\n/**\n * Delete a Kitty graphics image by ID.\n * Uses uppercase 'I' to also free the image data.\n */\nexport function deleteKittyImage(imageId: number): string {\n\treturn `\\x1b_Ga=d,d=I,i=${imageId},q=2\\x1b\\\\`;\n}\n\n/**\n * Delete all visible Kitty graphics images.\n * Uses uppercase 'A' to also free the image data.\n */\nexport function deleteAllKittyImages(): string {\n\treturn \"\\x1b_Ga=d,d=A,q=2\\x1b\\\\\";\n}\n\nexport function encodeITerm2(\n\tbase64Data: string,\n\toptions: {\n\t\twidth?: number | string;\n\t\theight?: number | string;\n\t\tname?: string;\n\t\tpreserveAspectRatio?: boolean;\n\t\tinline?: boolean;\n\t} = {},\n): string {\n\tconst params: string[] = [`inline=${options.inline !== false ? 1 : 0}`];\n\n\tif (options.width !== undefined) params.push(`width=${options.width}`);\n\tif (options.height !== undefined) params.push(`height=${options.height}`);\n\tif (options.name) {\n\t\tconst nameBase64 = Buffer.from(options.name).toString(\"base64\");\n\t\tparams.push(`name=${nameBase64}`);\n\t}\n\tif (options.preserveAspectRatio === false) {\n\t\tparams.push(\"preserveAspectRatio=0\");\n\t}\n\n\treturn `\\x1b]1337;File=${params.join(\";\")}:${base64Data}\\x07`;\n}\n\nexport interface ImageCellSize {\n\tcolumns: number;\n\trows: number;\n}\n\nexport function calculateImageCellSize(\n\timageDimensions: ImageDimensions,\n\tmaxWidthCells: number,\n\tmaxHeightCells?: number,\n\tcellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },\n): ImageCellSize {\n\tconst maxWidth = Math.max(1, Math.floor(maxWidthCells));\n\tconst maxHeight = maxHeightCells === undefined ? undefined : Math.max(1, Math.floor(maxHeightCells));\n\tconst imageWidth = Math.max(1, imageDimensions.widthPx);\n\tconst imageHeight = Math.max(1, imageDimensions.heightPx);\n\n\tconst widthScale = (maxWidth * cellDimensions.widthPx) / imageWidth;\n\tconst heightScale = maxHeight === undefined ? widthScale : (maxHeight * cellDimensions.heightPx) / imageHeight;\n\tconst scale = Math.min(widthScale, heightScale);\n\n\tconst scaledWidthPx = imageWidth * scale;\n\tconst scaledHeightPx = imageHeight * scale;\n\tconst columns = Math.ceil(scaledWidthPx / cellDimensions.widthPx);\n\tconst rows = Math.ceil(scaledHeightPx / cellDimensions.heightPx);\n\n\treturn {\n\t\tcolumns: Math.max(1, Math.min(maxWidth, columns)),\n\t\trows: Math.max(1, maxHeight === undefined ? rows : Math.min(maxHeight, rows)),\n\t};\n}\n\nexport function calculateImageRows(\n\timageDimensions: ImageDimensions,\n\ttargetWidthCells: number,\n\tcellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },\n): number {\n\treturn calculateImageCellSize(imageDimensions, targetWidthCells, undefined, cellDimensions).rows;\n}\n\nexport function getPngDimensions(base64Data: string): ImageDimensions | null {\n\ttry {\n\t\tconst buffer = Buffer.from(base64Data, \"base64\");\n\n\t\tif (buffer.length < 24) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (buffer[0] !== 0x89 || buffer[1] !== 0x50 || buffer[2] !== 0x4e || buffer[3] !== 0x47) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst width = buffer.readUInt32BE(16);\n\t\tconst height = buffer.readUInt32BE(20);\n\n\t\treturn { widthPx: width, heightPx: height };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function getJpegDimensions(base64Data: string): ImageDimensions | null {\n\ttry {\n\t\tconst buffer = Buffer.from(base64Data, \"base64\");\n\n\t\tif (buffer.length < 2) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (buffer[0] !== 0xff || buffer[1] !== 0xd8) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet offset = 2;\n\t\twhile (offset < buffer.length - 9) {\n\t\t\tif (buffer[offset] !== 0xff) {\n\t\t\t\toffset++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst marker = buffer[offset + 1];\n\n\t\t\tif (marker >= 0xc0 && marker <= 0xc2) {\n\t\t\t\tconst height = buffer.readUInt16BE(offset + 5);\n\t\t\t\tconst width = buffer.readUInt16BE(offset + 7);\n\t\t\t\treturn { widthPx: width, heightPx: height };\n\t\t\t}\n\n\t\t\tif (offset + 3 >= buffer.length) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst length = buffer.readUInt16BE(offset + 2);\n\t\t\tif (length < 2) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\toffset += 2 + length;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function getGifDimensions(base64Data: string): ImageDimensions | null {\n\ttry {\n\t\tconst buffer = Buffer.from(base64Data, \"base64\");\n\n\t\tif (buffer.length < 10) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst sig = buffer.slice(0, 6).toString(\"ascii\");\n\t\tif (sig !== \"GIF87a\" && sig !== \"GIF89a\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst width = buffer.readUInt16LE(6);\n\t\tconst height = buffer.readUInt16LE(8);\n\n\t\treturn { widthPx: width, heightPx: height };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function getWebpDimensions(base64Data: string): ImageDimensions | null {\n\ttry {\n\t\tconst buffer = Buffer.from(base64Data, \"base64\");\n\n\t\tif (buffer.length < 30) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst riff = buffer.slice(0, 4).toString(\"ascii\");\n\t\tconst webp = buffer.slice(8, 12).toString(\"ascii\");\n\t\tif (riff !== \"RIFF\" || webp !== \"WEBP\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst chunk = buffer.slice(12, 16).toString(\"ascii\");\n\t\tif (chunk === \"VP8 \") {\n\t\t\tif (buffer.length < 30) return null;\n\t\t\tconst width = buffer.readUInt16LE(26) & 0x3fff;\n\t\t\tconst height = buffer.readUInt16LE(28) & 0x3fff;\n\t\t\treturn { widthPx: width, heightPx: height };\n\t\t} else if (chunk === \"VP8L\") {\n\t\t\tif (buffer.length < 25) return null;\n\t\t\tconst bits = buffer.readUInt32LE(21);\n\t\t\tconst width = (bits & 0x3fff) + 1;\n\t\t\tconst height = ((bits >> 14) & 0x3fff) + 1;\n\t\t\treturn { widthPx: width, heightPx: height };\n\t\t} else if (chunk === \"VP8X\") {\n\t\t\tif (buffer.length < 30) return null;\n\t\t\tconst width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;\n\t\t\tconst height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;\n\t\t\treturn { widthPx: width, heightPx: height };\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function getImageDimensions(base64Data: string, mimeType: string): ImageDimensions | null {\n\tif (mimeType === \"image/png\") {\n\t\treturn getPngDimensions(base64Data);\n\t}\n\tif (mimeType === \"image/jpeg\") {\n\t\treturn getJpegDimensions(base64Data);\n\t}\n\tif (mimeType === \"image/gif\") {\n\t\treturn getGifDimensions(base64Data);\n\t}\n\tif (mimeType === \"image/webp\") {\n\t\treturn getWebpDimensions(base64Data);\n\t}\n\treturn null;\n}\n\nexport function renderImage(\n\tbase64Data: string,\n\timageDimensions: ImageDimensions,\n\toptions: ImageRenderOptions = {},\n): { sequence: string; rows: number; imageId?: number } | null {\n\tconst caps = getCapabilities();\n\n\tif (!caps.images) {\n\t\treturn null;\n\t}\n\n\tconst maxWidth = options.maxWidthCells ?? 80;\n\tconst size = calculateImageCellSize(imageDimensions, maxWidth, options.maxHeightCells, getCellDimensions());\n\n\tif (caps.images === \"kitty\") {\n\t\tconst sequence = encodeKitty(base64Data, {\n\t\t\tcolumns: size.columns,\n\t\t\trows: size.rows,\n\t\t\timageId: options.imageId,\n\t\t\tmoveCursor: options.moveCursor,\n\t\t});\n\t\treturn { sequence, rows: size.rows, imageId: options.imageId };\n\t}\n\n\tif (caps.images === \"iterm2\") {\n\t\tconst sequence = encodeITerm2(base64Data, {\n\t\t\twidth: size.columns,\n\t\t\theight: \"auto\",\n\t\t\tpreserveAspectRatio: options.preserveAspectRatio ?? true,\n\t\t});\n\t\treturn { sequence, rows: size.rows };\n\t}\n\n\treturn null;\n}\n\n/**\n * Wrap text in an OSC 8 hyperlink sequence.\n * The text is rendered as a clickable hyperlink in terminals that support OSC 8\n * (Ghostty, Kitty, WezTerm, iTerm2, VSCode, and others).\n * In terminals that do not support OSC 8, the escape sequences are ignored\n * and only the plain text is displayed.\n *\n * @param text - The visible text to display\n * @param url - The URL to link to\n */\nexport function hyperlink(text: string, url: string): string {\n\treturn `\\x1b]8;;${url}\\x1b\\\\${text}\\x1b]8;;\\x1b\\\\`;\n}\n\nexport function imageFallback(mimeType: string, dimensions?: ImageDimensions, filename?: string): string {\n\tconst parts: string[] = [];\n\tif (filename) parts.push(filename);\n\tparts.push(`[${mimeType}]`);\n\tif (dimensions) parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`);\n\treturn `[Image: ${parts.join(\" \")}]`;\n}\n"]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
export type KeyboardProtocolNegotiationSequence = {
|
|
2
|
+
type: "kitty-flags";
|
|
3
|
+
flags: number;
|
|
4
|
+
} | {
|
|
5
|
+
type: "device-attributes";
|
|
6
|
+
};
|
|
7
|
+
export declare function parseKeyboardProtocolNegotiationSequence(sequence: string): KeyboardProtocolNegotiationSequence | undefined;
|
|
8
|
+
export declare function isAppleTerminalSession(): boolean;
|
|
9
|
+
export declare function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string;
|
|
10
|
+
/**
|
|
11
|
+
* Minimal terminal interface for TUI
|
|
12
|
+
*/
|
|
13
|
+
export interface Terminal {
|
|
14
|
+
start(onInput: (data: string) => void, onResize: () => void): void;
|
|
15
|
+
stop(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Drain stdin before exiting to prevent Kitty key release events from
|
|
18
|
+
* leaking to the parent shell over slow SSH connections.
|
|
19
|
+
* @param maxMs - Maximum time to drain (default: 1000ms)
|
|
20
|
+
* @param idleMs - Exit early if no input arrives within this time (default: 50ms)
|
|
21
|
+
*/
|
|
22
|
+
drainInput(maxMs?: number, idleMs?: number): Promise<void>;
|
|
23
|
+
write(data: string): void;
|
|
24
|
+
get columns(): number;
|
|
25
|
+
get rows(): number;
|
|
26
|
+
get kittyProtocolActive(): boolean;
|
|
27
|
+
moveBy(lines: number): void;
|
|
28
|
+
hideCursor(): void;
|
|
29
|
+
showCursor(): void;
|
|
30
|
+
clearLine(): void;
|
|
31
|
+
clearFromCursor(): void;
|
|
32
|
+
clearScreen(): void;
|
|
33
|
+
setTitle(title: string): void;
|
|
34
|
+
setProgress(active: boolean): void;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Real terminal using process.stdin/stdout
|
|
38
|
+
*/
|
|
39
|
+
export declare class ProcessTerminal implements Terminal {
|
|
40
|
+
private wasRaw;
|
|
41
|
+
private inputHandler?;
|
|
42
|
+
private resizeHandler?;
|
|
43
|
+
private _kittyProtocolActive;
|
|
44
|
+
private _modifyOtherKeysActive;
|
|
45
|
+
private keyboardProtocolPushed;
|
|
46
|
+
private keyboardProtocolNegotiationPending;
|
|
47
|
+
private keyboardProtocolLateResponsePending;
|
|
48
|
+
private keyboardProtocolNegotiationBuffer;
|
|
49
|
+
private keyboardProtocolFallbackTimer?;
|
|
50
|
+
private keyboardProtocolBufferFlushTimer?;
|
|
51
|
+
private stdinBuffer?;
|
|
52
|
+
private stdinDataHandler?;
|
|
53
|
+
private progressInterval?;
|
|
54
|
+
private writeLogPath;
|
|
55
|
+
get kittyProtocolActive(): boolean;
|
|
56
|
+
start(onInput: (data: string) => void, onResize: () => void): void;
|
|
57
|
+
/**
|
|
58
|
+
* Set up StdinBuffer to split batched input into individual sequences.
|
|
59
|
+
* This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
|
|
60
|
+
*
|
|
61
|
+
* Also watches for Kitty protocol response and enables it when detected.
|
|
62
|
+
* This is done here (after stdinBuffer parsing) rather than on raw stdin
|
|
63
|
+
* to handle the case where the response arrives split across multiple events.
|
|
64
|
+
*/
|
|
65
|
+
private setupStdinBuffer;
|
|
66
|
+
/**
|
|
67
|
+
* Query terminal for Kitty keyboard protocol support and enable it if available.
|
|
68
|
+
*
|
|
69
|
+
* Kitty's progressive enhancement detection requires requesting the desired
|
|
70
|
+
* flags before querying them. The trailing DA query is a sentinel supported by
|
|
71
|
+
* terminals that do not know Kitty keyboard protocol. A short timeout remains
|
|
72
|
+
* as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop
|
|
73
|
+
* the DA response.
|
|
74
|
+
*
|
|
75
|
+
* The requested flags are:
|
|
76
|
+
* - 1 = disambiguate escape codes
|
|
77
|
+
* - 2 = report event types (press/repeat/release)
|
|
78
|
+
* - 4 = report alternate keys (shifted key, base layout key)
|
|
79
|
+
*/
|
|
80
|
+
private queryAndEnableKittyProtocol;
|
|
81
|
+
private handleKeyboardProtocolNegotiationSequence;
|
|
82
|
+
private readKeyboardProtocolNegotiationSequence;
|
|
83
|
+
private setKeyboardProtocolNegotiationBuffer;
|
|
84
|
+
private clearKeyboardProtocolNegotiationBuffer;
|
|
85
|
+
private flushKeyboardProtocolNegotiationBufferAsInput;
|
|
86
|
+
private scheduleKeyboardProtocolNegotiationBufferFlush;
|
|
87
|
+
private clearKeyboardProtocolNegotiationBufferFlushTimer;
|
|
88
|
+
private forwardInputSequence;
|
|
89
|
+
private enableModifyOtherKeys;
|
|
90
|
+
private clearKeyboardProtocolFallbackTimer;
|
|
91
|
+
/**
|
|
92
|
+
* On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
|
|
93
|
+
* console handle so the terminal sends VT sequences for modified keys
|
|
94
|
+
* (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
|
|
95
|
+
* discards modifier state and Shift+Tab arrives as plain \t.
|
|
96
|
+
*/
|
|
97
|
+
private enableWindowsVTInput;
|
|
98
|
+
drainInput(maxMs?: number, idleMs?: number): Promise<void>;
|
|
99
|
+
stop(): void;
|
|
100
|
+
write(data: string): void;
|
|
101
|
+
get columns(): number;
|
|
102
|
+
get rows(): number;
|
|
103
|
+
moveBy(lines: number): void;
|
|
104
|
+
hideCursor(): void;
|
|
105
|
+
showCursor(): void;
|
|
106
|
+
clearLine(): void;
|
|
107
|
+
clearFromCursor(): void;
|
|
108
|
+
clearScreen(): void;
|
|
109
|
+
setTitle(title: string): void;
|
|
110
|
+
setProgress(active: boolean): void;
|
|
111
|
+
private clearProgressInterval;
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=terminal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,mCAAmC,GAC5C;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,mBAAmB,CAAA;CAAE,CAAC;AAEjC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G,IAAI,CAS1B;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,SAAS,IAAI,IAAI,CAEhB;IAED,eAAe,IAAI,IAAI,CAEtB;IAED,WAAW,IAAI,IAAI,CAElB;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAG5B;IAED,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAcjC;IAED,OAAO,CAAC,qBAAqB;CAM7B","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { setKittyProtocolActive } from \"./keys.ts\";\nimport { isNativeModifierPressed } from \"./native-modifiers.ts\";\nimport { StdinBuffer } from \"./stdin-buffer.ts\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\nconst TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;\nconst TERMINAL_PROGRESS_ACTIVE_SEQUENCE = \"\\x1b]9;4;3\\x07\";\nconst TERMINAL_PROGRESS_CLEAR_SEQUENCE = \"\\x1b]9;4;0;\\x07\";\nconst APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = \"\\x1b[13;2u\";\nconst DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;\nconst KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS = 150;\nconst KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;\nconst KITTY_KEYBOARD_PROTOCOL_QUERY = `\\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\\x1b[?u\\x1b[c`;\n\nexport type KeyboardProtocolNegotiationSequence =\n\t| { type: \"kitty-flags\"; flags: number }\n\t| { type: \"device-attributes\" };\n\nexport function parseKeyboardProtocolNegotiationSequence(\n\tsequence: string,\n): KeyboardProtocolNegotiationSequence | undefined {\n\tconst kittyFlags = sequence.match(/^\\x1b\\[\\?(\\d+)u$/);\n\tif (kittyFlags) {\n\t\treturn { type: \"kitty-flags\", flags: Number.parseInt(kittyFlags[1]!, 10) };\n\t}\n\tif (/^\\x1b\\[\\?[\\d;]*c$/.test(sequence)) {\n\t\treturn { type: \"device-attributes\" };\n\t}\n\treturn undefined;\n}\n\nfunction isKeyboardProtocolNegotiationSequencePrefix(sequence: string, allowBareEscapePrefix: boolean): boolean {\n\treturn (allowBareEscapePrefix && sequence === \"\\x1b\") || sequence === \"\\x1b[\" || /^\\x1b\\[\\?[\\d;]*$/.test(sequence);\n}\n\nexport function isAppleTerminalSession(): boolean {\n\treturn process.platform === \"darwin\" && process.env.TERM_PROGRAM === \"Apple_Terminal\";\n}\n\nexport function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {\n\tif (isAppleTerminal && data === \"\\r\" && isShiftPressed) return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;\n\treturn data;\n}\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n\n\t// Progress indicator (OSC 9;4)\n\tsetProgress(active: boolean): void;\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate _modifyOtherKeysActive = false;\n\tprivate keyboardProtocolPushed = false;\n\tprivate keyboardProtocolNegotiationPending = false;\n\tprivate keyboardProtocolLateResponsePending = false;\n\tprivate keyboardProtocolNegotiationBuffer = \"\";\n\tprivate keyboardProtocolFallbackTimer?: ReturnType<typeof setTimeout>;\n\tprivate keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\n\tprivate progressInterval?: ReturnType<typeof setInterval>;\n\tprivate writeLogPath = (() => {\n\t\tconst env = process.env.PI_TUI_WRITE_LOG || \"\";\n\t\tif (!env) return \"\";\n\t\ttry {\n\t\t\tif (fs.statSync(env).isDirectory()) {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\n\t\t\t\treturn path.join(env, `tui-${ts}-${process.pid}.log`);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not an existing directory - use as-is (file path)\n\t\t}\n\t\treturn env;\n\t})();\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tprocess.stdout.write(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query and enable Kitty keyboard protocol\n\t\t// The query handler intercepts input temporarily, then installs the user's handler\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ timeout: 10 });\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\tif (this.keyboardProtocolNegotiationPending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, true);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\treturn; // Wait for the rest of a split negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.keyboardProtocolLateResponsePending) {\n\t\t\t\tconst negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence, false);\n\t\t\t\tif (negotiationSequence === \"pending\") {\n\t\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t\t\treturn; // Wait for the rest of a split late negotiation response.\n\t\t\t\t}\n\t\t\t\tif (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.forwardInputSequence(sequence);\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable it if available.\n\t *\n\t * Kitty's progressive enhancement detection requires requesting the desired\n\t * flags before querying them. The trailing DA query is a sentinel supported by\n\t * terminals that do not know Kitty keyboard protocol. A short timeout remains\n\t * as a backup for terminals, PTYs, and SSH sessions that delay, split, or drop\n\t * the DA response.\n\t *\n\t * The requested flags are:\n\t * - 1 = disambiguate escape codes\n\t * - 2 = report event types (press/repeat/release)\n\t * - 4 = report alternate keys (shifted key, base layout key)\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tthis.keyboardProtocolPushed = true;\n\t\tthis.keyboardProtocolNegotiationPending = true;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tprocess.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);\n\t\tthis.keyboardProtocolFallbackTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\tif (this.keyboardProtocolNegotiationBuffer === \"\\x1b\") {\n\t\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t\t} else {\n\t\t\t\tthis.scheduleKeyboardProtocolNegotiationBufferFlush();\n\t\t\t}\n\t\t\tthis.enableModifyOtherKeys();\n\t\t}, KITTY_KEYBOARD_PROTOCOL_FALLBACK_TIMEOUT_MS);\n\t}\n\n\tprivate handleKeyboardProtocolNegotiationSequence(\n\t\tnegotiationSequence: KeyboardProtocolNegotiationSequence | undefined,\n\t): boolean {\n\t\tif (!negotiationSequence) return false;\n\t\tif (negotiationSequence.type === \"kitty-flags\") {\n\t\t\tif (negotiationSequence.flags !== 0 && !this._kittyProtocolActive) {\n\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\tsetKittyProtocolActive(true);\n\t\t\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\t\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tthis.keyboardProtocolLateResponsePending = true;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tthis.enableModifyOtherKeys();\n\t\treturn true;\n\t}\n\n\tprivate readKeyboardProtocolNegotiationSequence(\n\t\tsequence: string,\n\t\tallowBareEscapePrefix: boolean,\n\t): KeyboardProtocolNegotiationSequence | \"pending\" | undefined {\n\t\tif (this.keyboardProtocolNegotiationBuffer) {\n\t\t\tconst bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;\n\t\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);\n\t\t\tif (negotiationSequence) {\n\t\t\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\t\t\treturn negotiationSequence;\n\t\t\t}\n\t\t\tif (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence, allowBareEscapePrefix)) {\n\t\t\t\tthis.setKeyboardProtocolNegotiationBuffer(bufferedSequence);\n\t\t\t\treturn \"pending\";\n\t\t\t}\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}\n\n\t\tconst negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);\n\t\tif (negotiationSequence) return negotiationSequence;\n\t\tif (isKeyboardProtocolNegotiationSequencePrefix(sequence, allowBareEscapePrefix)) {\n\t\t\tthis.setKeyboardProtocolNegotiationBuffer(sequence);\n\t\t\treturn \"pending\";\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate setKeyboardProtocolNegotiationBuffer(sequence: string): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = sequence;\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBuffer(): void {\n\t\tthis.clearKeyboardProtocolNegotiationBufferFlushTimer();\n\t\tthis.keyboardProtocolNegotiationBuffer = \"\";\n\t}\n\n\tprivate flushKeyboardProtocolNegotiationBufferAsInput(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer) return;\n\t\tconst sequence = this.keyboardProtocolNegotiationBuffer;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.forwardInputSequence(sequence);\n\t}\n\n\tprivate scheduleKeyboardProtocolNegotiationBufferFlush(): void {\n\t\tif (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;\n\t\tthis.keyboardProtocolBufferFlushTimer = setTimeout(() => {\n\t\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t\t\tthis.flushKeyboardProtocolNegotiationBufferAsInput();\n\t\t}, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);\n\t}\n\n\tprivate clearKeyboardProtocolNegotiationBufferFlushTimer(): void {\n\t\tif (!this.keyboardProtocolBufferFlushTimer) return;\n\t\tclearTimeout(this.keyboardProtocolBufferFlushTimer);\n\t\tthis.keyboardProtocolBufferFlushTimer = undefined;\n\t}\n\n\tprivate forwardInputSequence(sequence: string): void {\n\t\tif (!this.inputHandler) return;\n\t\tconst isAppleTerminal = sequence === \"\\r\" && isAppleTerminalSession();\n\t\tconst input = normalizeAppleTerminalInput(\n\t\t\tsequence,\n\t\t\tisAppleTerminal,\n\t\t\tisAppleTerminal && isNativeModifierPressed(\"shift\"),\n\t\t);\n\t\tthis.inputHandler(input);\n\t}\n\n\tprivate enableModifyOtherKeys(): void {\n\t\tif (this._kittyProtocolActive || this._modifyOtherKeysActive) return;\n\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\tthis._modifyOtherKeysActive = true;\n\t}\n\n\tprivate clearKeyboardProtocolFallbackTimer(): void {\n\t\tif (!this.keyboardProtocolFallbackTimer) return;\n\t\tclearTimeout(this.keyboardProtocolFallbackTimer);\n\t\tthis.keyboardProtocolFallbackTimer = undefined;\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\tconst arch = process.arch;\n\t\t\tif (arch !== \"x64\" && arch !== \"arm64\") return;\n\n\t\t\t// Dynamic require so non-Windows and bundled/browser paths never load the\n\t\t\t// native helper. In the npm package native/ is next to dist/; in compiled\n\t\t\t// binary archives native/ is copied next to the executable.\n\t\t\tconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\n\t\t\tconst nativePath = path.join(\"native\", \"win32\", \"prebuilds\", `win32-${arch}`, \"win32-console-mode.node\");\n\t\t\tconst candidates = [\n\t\t\t\tpath.join(moduleDir, \"..\", nativePath),\n\t\t\t\tpath.join(moduleDir, nativePath),\n\t\t\t\tpath.join(path.dirname(process.execPath), nativePath),\n\t\t\t];\n\t\t\tfor (const modulePath of candidates) {\n\t\t\t\ttry {\n\t\t\t\t\tconst helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };\n\t\t\t\t\thelper.enableVirtualTerminalInput?.();\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// Try the next possible packaging location.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Native helper not available — Shift+Tab won't be distinguishable from Tab.\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.clearProgressInterval()) {\n\t\t\tprocess.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\n\t\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\tconst shouldDisableKittyProtocol =\n\t\t\tthis.keyboardProtocolPushed || this._kittyProtocolActive || this.keyboardProtocolNegotiationPending;\n\t\tthis.keyboardProtocolLateResponsePending = false;\n\t\tthis.clearKeyboardProtocolNegotiationBuffer();\n\t\tthis.clearKeyboardProtocolFallbackTimer();\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (shouldDisableKittyProtocol) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis.keyboardProtocolPushed = false;\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\t\tthis.keyboardProtocolNegotiationPending = false;\n\t\tif (this._modifyOtherKeysActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;0m\");\n\t\t\tthis._modifyOtherKeysActive = false;\n\t\t}\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t}\n\t}\n\n\twrite(data: string): void {\n\t\tprocess.stdout.write(data);\n\t\tif (this.writeLogPath) {\n\t\t\ttry {\n\t\t\t\tfs.appendFileSync(this.writeLogPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t// Ignore logging errors\n\t\t\t}\n\t\t}\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || Number(process.env.COLUMNS) || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || Number(process.env.LINES) || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\t// Move down\n\t\t\tprocess.stdout.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\t// Move up\n\t\t\tprocess.stdout.write(`\\x1b[${-lines}A`);\n\t\t}\n\t\t// lines === 0: no movement\n\t}\n\n\thideCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tprocess.stdout.write(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tprocess.stdout.write(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\t// OSC 0;title BEL - set terminal window title\n\t\tprocess.stdout.write(`\\x1b]0;${title}\\x07`);\n\t}\n\n\tsetProgress(active: boolean): void {\n\t\tif (active) {\n\t\t\t// OSC 9;4;3 - indeterminate progress\n\t\t\tprocess.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\tif (!this.progressInterval) {\n\t\t\t\tthis.progressInterval = setInterval(() => {\n\t\t\t\t\tprocess.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);\n\t\t\t\t}, TERMINAL_PROGRESS_KEEPALIVE_MS);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.clearProgressInterval();\n\t\t\t// OSC 9;4;0 - clear progress\n\t\t\tprocess.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);\n\t\t}\n\t}\n\n\tprivate clearProgressInterval(): boolean {\n\t\tif (!this.progressInterval) return false;\n\t\tclearInterval(this.progressInterval);\n\t\tthis.progressInterval = undefined;\n\t\treturn true;\n\t}\n}\n"]}
|