@mariozechner/pi-tui 0.67.4 → 0.67.6
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/dist/autocomplete.d.ts +1 -0
- package/dist/autocomplete.d.ts.map +1 -1
- package/dist/autocomplete.js +11 -5
- package/dist/autocomplete.js.map +1 -1
- package/dist/components/markdown.d.ts.map +1 -1
- package/dist/components/markdown.js +17 -12
- package/dist/components/markdown.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/terminal-image.d.ts +13 -0
- package/dist/terminal-image.d.ts.map +1 -1
- package/dist/terminal-image.js +31 -1
- package/dist/terminal-image.js.map +1 -1
- package/dist/terminal.d.ts.map +1 -1
- package/dist/terminal.js +0 -9
- package/dist/terminal.js.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +26 -11
- package/dist/utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminal-image.js","sourceRoot":"","sources":["../src/terminal-image.ts"],"names":[],"mappings":"AA0BA,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,MAAM,UAAU,kBAAkB,GAAyB;IAC1D,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;IAClE,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,WAAW,EAAE,I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AE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;QAChG,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC;IACrD,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,QAAQ,GAAG,YAAY,CAAC,UAAU,EAAE;YACzC,KAAK,EAAE,QAAQ;YACf,MAAM,EAAE,MAAM;YACd,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,IAAI;SACxD,CAAC,CAAC;QACH,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;IAED,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,UAA4B,EAAE,QAAiB,EAAU;IACxG,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,QAAQ;QAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,KAAK,CAAC,IAAI,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAC;IAC5B,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":["export 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}\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\nexport function detectCapabilities(): TerminalCapabilities {\n\tconst termProgram = process.env.TERM_PROGRAM?.toLowerCase() || \"\";\n\tconst term = process.env.TERM?.toLowerCase() || \"\";\n\tconst colorTerm = process.env.COLORTERM?.toLowerCase() || \"\";\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 (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\tconst trueColor = colorTerm === \"truecolor\" || colorTerm === \"24bit\";\n\treturn { images: null, trueColor, hyperlinks: true };\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\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} = {},\n): string {\n\tconst CHUNK_SIZE = 4096;\n\n\tconst params: string[] = [\"a=T\", \"f=100\", \"q=2\"];\n\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}\\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\\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 function calculateImageRows(\n\timageDimensions: ImageDimensions,\n\ttargetWidthCells: number,\n\tcellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },\n): number {\n\tconst targetWidthPx = targetWidthCells * cellDimensions.widthPx;\n\tconst scale = targetWidthPx / imageDimensions.widthPx;\n\tconst scaledHeightPx = imageDimensions.heightPx * scale;\n\tconst rows = Math.ceil(scaledHeightPx / cellDimensions.heightPx);\n\treturn Math.max(1, 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 rows = calculateImageRows(imageDimensions, maxWidth, getCellDimensions());\n\n\tif (caps.images === \"kitty\") {\n\t\t// Only use imageId if explicitly provided - static images don't need IDs\n\t\tconst sequence = encodeKitty(base64Data, { columns: maxWidth, rows, imageId: options.imageId });\n\t\treturn { sequence, rows, imageId: options.imageId };\n\t}\n\n\tif (caps.images === \"iterm2\") {\n\t\tconst sequence = encodeITerm2(base64Data, {\n\t\t\twidth: maxWidth,\n\t\t\theight: \"auto\",\n\t\t\tpreserveAspectRatio: options.preserveAspectRatio ?? true,\n\t\t});\n\t\treturn { sequence, rows };\n\t}\n\n\treturn null;\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"]}
|
|
1
|
+
{"version":3,"file":"terminal-image.js","sourceRoot":"","sources":["../src/terminal-image.ts"],"names":[],"mappings":"AA0BA,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,MAAM,UAAU,kBAAkB,GAAyB;IAC1D,MAAM,WAAW,GAAG,OAAO,CAAC,GA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AU,SAAS,CAAC,IAAY,EAAE,GAAW,EAAU;IAC5D,OAAO,WAAW,GAAG,SAAS,IAAI,gBAAgB,CAAC;AAAA,CACnD;AAED,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,UAA4B,EAAE,QAAiB,EAAU;IACxG,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,QAAQ;QAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,KAAK,CAAC,IAAI,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAC;IAC5B,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":["export 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}\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\nexport function detectCapabilities(): TerminalCapabilities {\n\tconst termProgram = process.env.TERM_PROGRAM?.toLowerCase() || \"\";\n\tconst term = process.env.TERM?.toLowerCase() || \"\";\n\tconst colorTerm = process.env.COLORTERM?.toLowerCase() || \"\";\n\n\t// tmux and screen swallow OSC 8 by default (passthrough is opt-in and wraps\n\t// sequences differently). Force hyperlinks off whenever we detect them, even\n\t// when the outer terminal would otherwise support OSC 8. Image protocols are\n\t// also unreliable under tmux/screen, so leave `images: null` for safety.\n\tconst inTmuxOrScreen = !!process.env.TMUX || term.startsWith(\"tmux\") || term.startsWith(\"screen\");\n\tif (inTmuxOrScreen) {\n\t\tconst trueColor = colorTerm === \"truecolor\" || colorTerm === \"24bit\";\n\t\treturn { images: null, trueColor, 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 (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\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\tconst trueColor = colorTerm === \"truecolor\" || colorTerm === \"24bit\";\n\treturn { images: null, trueColor, 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} = {},\n): string {\n\tconst CHUNK_SIZE = 4096;\n\n\tconst params: string[] = [\"a=T\", \"f=100\", \"q=2\"];\n\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}\\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\\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 function calculateImageRows(\n\timageDimensions: ImageDimensions,\n\ttargetWidthCells: number,\n\tcellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 },\n): number {\n\tconst targetWidthPx = targetWidthCells * cellDimensions.widthPx;\n\tconst scale = targetWidthPx / imageDimensions.widthPx;\n\tconst scaledHeightPx = imageDimensions.heightPx * scale;\n\tconst rows = Math.ceil(scaledHeightPx / cellDimensions.heightPx);\n\treturn Math.max(1, 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 rows = calculateImageRows(imageDimensions, maxWidth, getCellDimensions());\n\n\tif (caps.images === \"kitty\") {\n\t\t// Only use imageId if explicitly provided - static images don't need IDs\n\t\tconst sequence = encodeKitty(base64Data, { columns: maxWidth, rows, imageId: options.imageId });\n\t\treturn { sequence, rows, imageId: options.imageId };\n\t}\n\n\tif (caps.images === \"iterm2\") {\n\t\tconst sequence = encodeITerm2(base64Data, {\n\t\t\twidth: maxWidth,\n\t\t\theight: \"auto\",\n\t\t\tpreserveAspectRatio: options.preserveAspectRatio ?? true,\n\t\t});\n\t\treturn { sequence, 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(\" \")}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AI,OAAO,CAEjC;IAED,KAAK,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAkCjE;IAED;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB;IA2CxB;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,2BAA2B;IAuBnC;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAuBtB,UAAU,CAAC,KAAK,SAAO,EAAE,MAAM,SAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAoCzD;IAED,IAAI,IAAI,IAAI,CAyCX;IAED,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CASxB;IAED,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,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;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.js\";\nimport { StdinBuffer } from \"./stdin-buffer.js\";\n\nconst cjsRequire = createRequire(import.meta.url);\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\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 stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\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// Kitty protocol response pattern: \\x1b[?<flags>u\n\t\tconst kittyResponsePattern = /^\\x1b\\[\\?(\\d+)u$/;\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\t// Check for Kitty protocol response (only if not already enabled)\n\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\tconst match = sequence.match(kittyResponsePattern);\n\t\t\t\tif (match) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\n\t\t\t\t\t// Enable Kitty keyboard protocol (push flags)\n\t\t\t\t\t// Flag 1 = disambiguate escape codes\n\t\t\t\t\t// Flag 2 = report event types (press/repeat/release)\n\t\t\t\t\t// Flag 4 = report alternate keys (shifted key, base layout key)\n\t\t\t\t\t// Base layout key enables shortcuts to work with non-Latin keyboard layouts\n\t\t\t\t\tprocess.stdout.write(\"\\x1b[>7u\");\n\t\t\t\t\treturn; // Don't forward protocol response to TUI\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(sequence);\n\t\t\t}\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 if available.\n\t *\n\t * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,\n\t * it supports the protocol and we enable it with CSI > 1 u.\n\t *\n\t * If no Kitty response arrives shortly after startup, fall back to enabling\n\t * xterm modifyOtherKeys mode 2. This is needed for tmux, which can forward\n\t * modified enter keys as CSI-u when extended-keys is enabled, but may not\n\t * answer the Kitty protocol query.\n\t *\n\t * The response is detected in setupStdinBuffer's data handler, which properly\n\t * handles the case where the response arrives split across multiple stdin events.\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\n\t\t// Zellij forwards the Kitty query to the outer terminal, which can make\n\t\t// Pi enable its Kitty parser even though Zellij still sends Alt as\n\t\t// legacy ESC-prefixed sequences. Skip the Kitty query there and use\n\t\t// modifyOtherKeys directly instead.\n\t\tif (process.env.ZELLIJ) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\treturn;\n\t\t}\n\n\t\tprocess.stdout.write(\"\\x1b[?u\");\n\t\tsetTimeout(() => {\n\t\t\tif (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {\n\t\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\t}\n\t\t}, 150);\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\t// Dynamic require to avoid bundling koffi's 74MB of cross-platform\n\t\t\t// native binaries into every compiled binary. Koffi is only needed\n\t\t\t// on Windows for VT input support.\n\t\t\tconst koffi = cjsRequire(\"koffi\");\n\t\t\tconst k32 = koffi.load(\"kernel32.dll\");\n\t\t\tconst GetStdHandle = k32.func(\"void* __stdcall GetStdHandle(int)\");\n\t\t\tconst GetConsoleMode = k32.func(\"bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)\");\n\t\t\tconst SetConsoleMode = k32.func(\"bool __stdcall SetConsoleMode(void*, uint32_t)\");\n\n\t\t\tconst STD_INPUT_HANDLE = -10;\n\t\t\tconst ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;\n\t\t\tconst handle = GetStdHandle(STD_INPUT_HANDLE);\n\t\t\tconst mode = new Uint32Array(1);\n\t\t\tGetConsoleMode(handle, mode);\n\t\t\tSetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);\n\t\t} catch {\n\t\t\t// koffi 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\tif (this._kittyProtocolActive) {\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._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (this._kittyProtocolActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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 || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || 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"]}
|
|
1
|
+
{"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAQA;;GAEG;AACH,MAAM,WAAW,QAAQ;IAExB,KAAK,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAGnE,IAAI,IAAI,IAAI,CAAC;IAEb;;;;;OAKG;IACH,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAG3D,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAG1B,IAAI,OAAO,IAAI,MAAM,CAAC;IACtB,IAAI,IAAI,IAAI,MAAM,CAAC;IAGnB,IAAI,mBAAmB,IAAI,OAAO,CAAC;IAGnC,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAG5B,UAAU,IAAI,IAAI,CAAC;IACnB,UAAU,IAAI,IAAI,CAAC;IAGnB,SAAS,IAAI,IAAI,CAAC;IAClB,eAAe,IAAI,IAAI,CAAC;IACxB,WAAW,IAAI,IAAI,CAAC;IAGpB,QAAQ,CA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"node:path\";\nimport { setKittyProtocolActive } from \"./keys.js\";\nimport { StdinBuffer } from \"./stdin-buffer.js\";\n\nconst cjsRequire = createRequire(import.meta.url);\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\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 stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\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// Kitty protocol response pattern: \\x1b[?<flags>u\n\t\tconst kittyResponsePattern = /^\\x1b\\[\\?(\\d+)u$/;\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\t// Check for Kitty protocol response (only if not already enabled)\n\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\tconst match = sequence.match(kittyResponsePattern);\n\t\t\t\tif (match) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\n\t\t\t\t\t// Enable Kitty keyboard protocol (push flags)\n\t\t\t\t\t// Flag 1 = disambiguate escape codes\n\t\t\t\t\t// Flag 2 = report event types (press/repeat/release)\n\t\t\t\t\t// Flag 4 = report alternate keys (shifted key, base layout key)\n\t\t\t\t\t// Base layout key enables shortcuts to work with non-Latin keyboard layouts\n\t\t\t\t\tprocess.stdout.write(\"\\x1b[>7u\");\n\t\t\t\t\treturn; // Don't forward protocol response to TUI\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(sequence);\n\t\t\t}\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 if available.\n\t *\n\t * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,\n\t * it supports the protocol and we enable it with CSI > 1 u.\n\t *\n\t * If no Kitty response arrives shortly after startup, fall back to enabling\n\t * xterm modifyOtherKeys mode 2. This is needed for tmux, which can forward\n\t * modified enter keys as CSI-u when extended-keys is enabled, but may not\n\t * answer the Kitty protocol query.\n\t *\n\t * The response is detected in setupStdinBuffer's data handler, which properly\n\t * handles the case where the response arrives split across multiple stdin events.\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tprocess.stdout.write(\"\\x1b[?u\");\n\t\tsetTimeout(() => {\n\t\t\tif (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {\n\t\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\t}\n\t\t}, 150);\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\t// Dynamic require to avoid bundling koffi's 74MB of cross-platform\n\t\t\t// native binaries into every compiled binary. Koffi is only needed\n\t\t\t// on Windows for VT input support.\n\t\t\tconst koffi = cjsRequire(\"koffi\");\n\t\t\tconst k32 = koffi.load(\"kernel32.dll\");\n\t\t\tconst GetStdHandle = k32.func(\"void* __stdcall GetStdHandle(int)\");\n\t\t\tconst GetConsoleMode = k32.func(\"bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)\");\n\t\t\tconst SetConsoleMode = k32.func(\"bool __stdcall SetConsoleMode(void*, uint32_t)\");\n\n\t\t\tconst STD_INPUT_HANDLE = -10;\n\t\t\tconst ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;\n\t\t\tconst handle = GetStdHandle(STD_INPUT_HANDLE);\n\t\t\tconst mode = new Uint32Array(1);\n\t\t\tGetConsoleMode(handle, mode);\n\t\t\tSetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);\n\t\t} catch {\n\t\t\t// koffi 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\tif (this._kittyProtocolActive) {\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._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (this._kittyProtocolActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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 || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || 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"]}
|
package/dist/terminal.js
CHANGED
|
@@ -124,15 +124,6 @@ export class ProcessTerminal {
|
|
|
124
124
|
queryAndEnableKittyProtocol() {
|
|
125
125
|
this.setupStdinBuffer();
|
|
126
126
|
process.stdin.on("data", this.stdinDataHandler);
|
|
127
|
-
// Zellij forwards the Kitty query to the outer terminal, which can make
|
|
128
|
-
// Pi enable its Kitty parser even though Zellij still sends Alt as
|
|
129
|
-
// legacy ESC-prefixed sequences. Skip the Kitty query there and use
|
|
130
|
-
// modifyOtherKeys directly instead.
|
|
131
|
-
if (process.env.ZELLIJ) {
|
|
132
|
-
process.stdout.write("\x1b[>4;2m");
|
|
133
|
-
this._modifyOtherKeysActive = true;
|
|
134
|
-
return;
|
|
135
|
-
}
|
|
136
127
|
process.stdout.write("\x1b[?u");
|
|
137
128
|
setTimeout(() => {
|
|
138
129
|
if (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {
|
package/dist/terminal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminal.js","sourceRoot":"","sources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from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.js\";\nimport { StdinBuffer } from \"./stdin-buffer.js\";\n\nconst cjsRequire = createRequire(import.meta.url);\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\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 stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\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// Kitty protocol response pattern: \\x1b[?<flags>u\n\t\tconst kittyResponsePattern = /^\\x1b\\[\\?(\\d+)u$/;\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\t// Check for Kitty protocol response (only if not already enabled)\n\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\tconst match = sequence.match(kittyResponsePattern);\n\t\t\t\tif (match) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\n\t\t\t\t\t// Enable Kitty keyboard protocol (push flags)\n\t\t\t\t\t// Flag 1 = disambiguate escape codes\n\t\t\t\t\t// Flag 2 = report event types (press/repeat/release)\n\t\t\t\t\t// Flag 4 = report alternate keys (shifted key, base layout key)\n\t\t\t\t\t// Base layout key enables shortcuts to work with non-Latin keyboard layouts\n\t\t\t\t\tprocess.stdout.write(\"\\x1b[>7u\");\n\t\t\t\t\treturn; // Don't forward protocol response to TUI\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(sequence);\n\t\t\t}\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 if available.\n\t *\n\t * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,\n\t * it supports the protocol and we enable it with CSI > 1 u.\n\t *\n\t * If no Kitty response arrives shortly after startup, fall back to enabling\n\t * xterm modifyOtherKeys mode 2. This is needed for tmux, which can forward\n\t * modified enter keys as CSI-u when extended-keys is enabled, but may not\n\t * answer the Kitty protocol query.\n\t *\n\t * The response is detected in setupStdinBuffer's data handler, which properly\n\t * handles the case where the response arrives split across multiple stdin events.\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\n\t\t// Zellij forwards the Kitty query to the outer terminal, which can make\n\t\t// Pi enable its Kitty parser even though Zellij still sends Alt as\n\t\t// legacy ESC-prefixed sequences. Skip the Kitty query there and use\n\t\t// modifyOtherKeys directly instead.\n\t\tif (process.env.ZELLIJ) {\n\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\treturn;\n\t\t}\n\n\t\tprocess.stdout.write(\"\\x1b[?u\");\n\t\tsetTimeout(() => {\n\t\t\tif (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {\n\t\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\t}\n\t\t}, 150);\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\t// Dynamic require to avoid bundling koffi's 74MB of cross-platform\n\t\t\t// native binaries into every compiled binary. Koffi is only needed\n\t\t\t// on Windows for VT input support.\n\t\t\tconst koffi = cjsRequire(\"koffi\");\n\t\t\tconst k32 = koffi.load(\"kernel32.dll\");\n\t\t\tconst GetStdHandle = k32.func(\"void* __stdcall GetStdHandle(int)\");\n\t\t\tconst GetConsoleMode = k32.func(\"bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)\");\n\t\t\tconst SetConsoleMode = k32.func(\"bool __stdcall SetConsoleMode(void*, uint32_t)\");\n\n\t\t\tconst STD_INPUT_HANDLE = -10;\n\t\t\tconst ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;\n\t\t\tconst handle = GetStdHandle(STD_INPUT_HANDLE);\n\t\t\tconst mode = new Uint32Array(1);\n\t\t\tGetConsoleMode(handle, mode);\n\t\t\tSetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);\n\t\t} catch {\n\t\t\t// koffi 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\tif (this._kittyProtocolActive) {\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._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (this._kittyProtocolActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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 || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || 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"]}
|
|
1
|
+
{"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,UAAU,GAAG,aAAa,CAAC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AQ,CAAC,KAAK,GAAG,CAAC,CAAC;QACzC,CAAC;QACD,2BAA2B;IAD1B,CAED;IAED,UAAU,GAAS;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAAA,CAClC;IAED,UAAU,GAAS;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAAA,CAClC;IAED,SAAS,GAAS;QACjB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC/B;IAED,eAAe,GAAS;QACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC/B;IAED,WAAW,GAAS;QACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC,sCAAsC;IAAvC,CACtC;IAED,QAAQ,CAAC,KAAa,EAAQ;QAC7B,8CAA8C;QAC9C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,KAAK,MAAM,CAAC,CAAC;IAAA,CAC5C;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { setKittyProtocolActive } from \"./keys.js\";\nimport { StdinBuffer } from \"./stdin-buffer.js\";\n\nconst cjsRequire = createRequire(import.meta.url);\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\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 stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\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// Kitty protocol response pattern: \\x1b[?<flags>u\n\t\tconst kittyResponsePattern = /^\\x1b\\[\\?(\\d+)u$/;\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\t// Check for Kitty protocol response (only if not already enabled)\n\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\tconst match = sequence.match(kittyResponsePattern);\n\t\t\t\tif (match) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\n\t\t\t\t\t// Enable Kitty keyboard protocol (push flags)\n\t\t\t\t\t// Flag 1 = disambiguate escape codes\n\t\t\t\t\t// Flag 2 = report event types (press/repeat/release)\n\t\t\t\t\t// Flag 4 = report alternate keys (shifted key, base layout key)\n\t\t\t\t\t// Base layout key enables shortcuts to work with non-Latin keyboard layouts\n\t\t\t\t\tprocess.stdout.write(\"\\x1b[>7u\");\n\t\t\t\t\treturn; // Don't forward protocol response to TUI\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(sequence);\n\t\t\t}\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 if available.\n\t *\n\t * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,\n\t * it supports the protocol and we enable it with CSI > 1 u.\n\t *\n\t * If no Kitty response arrives shortly after startup, fall back to enabling\n\t * xterm modifyOtherKeys mode 2. This is needed for tmux, which can forward\n\t * modified enter keys as CSI-u when extended-keys is enabled, but may not\n\t * answer the Kitty protocol query.\n\t *\n\t * The response is detected in setupStdinBuffer's data handler, which properly\n\t * handles the case where the response arrives split across multiple stdin events.\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tprocess.stdout.write(\"\\x1b[?u\");\n\t\tsetTimeout(() => {\n\t\t\tif (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {\n\t\t\t\tprocess.stdout.write(\"\\x1b[>4;2m\");\n\t\t\t\tthis._modifyOtherKeysActive = true;\n\t\t\t}\n\t\t}, 150);\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\t// Dynamic require to avoid bundling koffi's 74MB of cross-platform\n\t\t\t// native binaries into every compiled binary. Koffi is only needed\n\t\t\t// on Windows for VT input support.\n\t\t\tconst koffi = cjsRequire(\"koffi\");\n\t\t\tconst k32 = koffi.load(\"kernel32.dll\");\n\t\t\tconst GetStdHandle = k32.func(\"void* __stdcall GetStdHandle(int)\");\n\t\t\tconst GetConsoleMode = k32.func(\"bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)\");\n\t\t\tconst SetConsoleMode = k32.func(\"bool __stdcall SetConsoleMode(void*, uint32_t)\");\n\n\t\t\tconst STD_INPUT_HANDLE = -10;\n\t\t\tconst ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;\n\t\t\tconst handle = GetStdHandle(STD_INPUT_HANDLE);\n\t\t\tconst mode = new Uint32Array(1);\n\t\t\tGetConsoleMode(handle, mode);\n\t\t\tSetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);\n\t\t} catch {\n\t\t\t// koffi 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\tif (this._kittyProtocolActive) {\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._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (this._kittyProtocolActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\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 || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || 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"]}
|
package/dist/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,wBAAgB,YAAY,IAAI,IAAI,CAAC,SAAS,CAE7C;AAyLD;;GAEG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAuDhD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAsCjG;AA+QD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAoBtE;AAmFD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEvD;AAuED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CASzG;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,QAAQ,GAAE,MAAc,EACxB,GAAG,GAAE,OAAe,GAClB,MAAM,CAmIR;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAQ,GAAG,MAAM,CAEpG;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,UAAQ,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAwCjC;AAKD;;;;GAIG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,WAAW,UAAQ,GACjB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAiE5E","sourcesContent":["import { eastAsianWidth } from \"get-east-asian-width\";\n\n// Grapheme segmenter (shared instance)\nconst segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\n/**\n * Get the shared grapheme segmenter instance.\n */\nexport function getSegmenter(): Intl.Segmenter {\n\treturn segmenter;\n}\n\n/**\n * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji.\n * This is a fast heuristic to avoid the expensive rgiEmojiRegex test.\n * The tested Unicode blocks are deliberately broad to account for future\n * Unicode additions.\n */\nfunction couldBeEmoji(segment: string): boolean {\n\tconst cp = segment.codePointAt(0)!;\n\treturn (\n\t\t(cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph\n\t\t(cp >= 0x2300 && cp <= 0x23ff) || // Misc technical\n\t\t(cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats\n\t\t(cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles\n\t\tsegment.includes(\"\\uFE0F\") || // Contains VS16 (emoji presentation selector)\n\t\tsegment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.)\n\t);\n}\n\n// Regexes for character classification (same as string-width library)\nconst zeroWidthRegex = /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$/v;\nconst leadingNonPrintingRegex = /^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+/v;\nconst rgiEmojiRegex = /^\\p{RGI_Emoji}$/v;\n\n// Cache for non-ASCII strings\nconst WIDTH_CACHE_SIZE = 512;\nconst widthCache = new Map<string, number>();\n\nfunction isPrintableAscii(str: string): boolean {\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst code = str.charCodeAt(i);\n\t\tif (code < 0x20 || code > 0x7e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {\n\tif (maxWidth <= 0 || text.length === 0) {\n\t\treturn { text: \"\", width: 0 };\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tconst clipped = text.slice(0, maxWidth);\n\t\treturn { text: clipped, width: clipped.length };\n\t}\n\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\tif (!hasAnsi && !hasTabs) {\n\t\tlet result = \"\";\n\t\tlet width = 0;\n\t\tfor (const { segment } of segmenter.segment(text)) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\treturn { text: result, width };\n\t}\n\n\tlet result = \"\";\n\tlet width = 0;\n\tlet i = 0;\n\tlet pendingAnsi = \"\";\n\n\twhile (i < text.length) {\n\t\tconst ansi = extractAnsiCode(text, i);\n\t\tif (ansi) {\n\t\t\tpendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (text[i] === \"\\t\") {\n\t\t\tif (width + 3 > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += \"\\t\";\n\t\t\twidth += 3;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet end = i;\n\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\tif (nextAnsi) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tend++;\n\t\t}\n\n\t\tfor (const { segment } of segmenter.segment(text.slice(i, end))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\treturn { text: result, width };\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\ti = end;\n\t}\n\n\treturn { text: result, width };\n}\n\nfunction finalizeTruncatedResult(\n\tprefix: string,\n\tprefixWidth: number,\n\tellipsis: string,\n\tellipsisWidth: number,\n\tmaxWidth: number,\n\tpad: boolean,\n): string {\n\tconst reset = \"\\x1b[0m\";\n\tconst visibleWidth = prefixWidth + ellipsisWidth;\n\tlet result: string;\n\n\tif (ellipsis.length > 0) {\n\t\tresult = `${prefix}${reset}${ellipsis}${reset}`;\n\t} else {\n\t\tresult = `${prefix}${reset}`;\n\t}\n\n\treturn pad ? result + \" \".repeat(Math.max(0, maxWidth - visibleWidth)) : result;\n}\n\n/**\n * Calculate the terminal width of a single grapheme cluster.\n * Based on code from the string-width library, but includes a possible-emoji\n * check to avoid running the RGI_Emoji regex unnecessarily.\n */\nfunction graphemeWidth(segment: string): number {\n\t// Zero-width clusters\n\tif (zeroWidthRegex.test(segment)) {\n\t\treturn 0;\n\t}\n\n\t// Emoji check with pre-filter\n\tif (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {\n\t\treturn 2;\n\t}\n\n\t// Get base visible codepoint\n\tconst base = segment.replace(leadingNonPrintingRegex, \"\");\n\tconst cp = base.codePointAt(0);\n\tif (cp === undefined) {\n\t\treturn 0;\n\t}\n\n\t// Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as\n\t// full-width emoji in terminals, even when isolated during streaming.\n\t// Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.\n\tif (cp >= 0x1f1e6 && cp <= 0x1f1ff) {\n\t\treturn 2;\n\t}\n\n\tlet width = eastAsianWidth(cp);\n\n\t// Trailing halfwidth/fullwidth forms\n\tif (segment.length > 1) {\n\t\tfor (const char of segment.slice(1)) {\n\t\t\tconst c = char.codePointAt(0)!;\n\t\t\tif (c >= 0xff00 && c <= 0xffef) {\n\t\t\t\twidth += eastAsianWidth(c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn width;\n}\n\n/**\n * Calculate the visible width of a string in terminal columns.\n */\nexport function visibleWidth(str: string): number {\n\tif (str.length === 0) {\n\t\treturn 0;\n\t}\n\n\t// Fast path: pure ASCII printable\n\tif (isPrintableAscii(str)) {\n\t\treturn str.length;\n\t}\n\n\t// Check cache\n\tconst cached = widthCache.get(str);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Normalize: tabs to 3 spaces, strip ANSI escape codes\n\tlet clean = str;\n\tif (str.includes(\"\\t\")) {\n\t\tclean = clean.replace(/\\t/g, \" \");\n\t}\n\tif (clean.includes(\"\\x1b\")) {\n\t\t// Strip supported ANSI/OSC/APC escape sequences in one pass.\n\t\t// This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,\n\t\t// and APC sequences like CURSOR_MARKER.\n\t\tlet stripped = \"\";\n\t\tlet i = 0;\n\t\twhile (i < clean.length) {\n\t\t\tconst ansi = extractAnsiCode(clean, i);\n\t\t\tif (ansi) {\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstripped += clean[i];\n\t\t\ti++;\n\t\t}\n\t\tclean = stripped;\n\t}\n\n\t// Calculate width\n\tlet width = 0;\n\tfor (const { segment } of segmenter.segment(clean)) {\n\t\twidth += graphemeWidth(segment);\n\t}\n\n\t// Cache result\n\tif (widthCache.size >= WIDTH_CACHE_SIZE) {\n\t\tconst firstKey = widthCache.keys().next().value;\n\t\tif (firstKey !== undefined) {\n\t\t\twidthCache.delete(firstKey);\n\t\t}\n\t}\n\twidthCache.set(str, width);\n\n\treturn width;\n}\n\n/**\n * Extract ANSI escape sequences from a string at the given position.\n */\nexport function extractAnsiCode(str: string, pos: number): { code: string; length: number } | null {\n\tif (pos >= str.length || str[pos] !== \"\\x1b\") return null;\n\n\tconst next = str[pos + 1];\n\n\t// CSI sequence: ESC [ ... m/G/K/H/J\n\tif (next === \"[\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;\n\t\tif (j < str.length) return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\treturn null;\n\t}\n\n\t// OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \\)\n\t// Used for hyperlinks (OSC 8), window titles, etc.\n\tif (next === \"]\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\t// APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \\)\n\t// Used for cursor marker and application-specific commands\n\tif (next === \"_\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn null;\n}\n\n/**\n * Track active ANSI SGR codes to preserve styling across line breaks.\n */\nclass AnsiCodeTracker {\n\t// Track individual attributes separately so we can reset them specifically\n\tprivate bold = false;\n\tprivate dim = false;\n\tprivate italic = false;\n\tprivate underline = false;\n\tprivate blink = false;\n\tprivate inverse = false;\n\tprivate hidden = false;\n\tprivate strikethrough = false;\n\tprivate fgColor: string | null = null; // Stores the full code like \"31\" or \"38;5;240\"\n\tprivate bgColor: string | null = null; // Stores the full code like \"41\" or \"48;5;240\"\n\n\tprocess(ansiCode: string): void {\n\t\tif (!ansiCode.endsWith(\"m\")) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Extract the parameters between \\x1b[ and m\n\t\tconst match = ansiCode.match(/\\x1b\\[([\\d;]*)m/);\n\t\tif (!match) return;\n\n\t\tconst params = match[1];\n\t\tif (params === \"\" || params === \"0\") {\n\t\t\t// Full reset\n\t\t\tthis.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Parse parameters (can be semicolon-separated)\n\t\tconst parts = params.split(\";\");\n\t\tlet i = 0;\n\t\twhile (i < parts.length) {\n\t\t\tconst code = Number.parseInt(parts[i], 10);\n\n\t\t\t// Handle 256-color and RGB codes which consume multiple parameters\n\t\t\tif (code === 38 || code === 48) {\n\t\t\t\t// 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg)\n\t\t\t\t// 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg)\n\t\t\t\tif (parts[i + 1] === \"5\" && parts[i + 2] !== undefined) {\n\t\t\t\t\t// 256 color: 38;5;N or 48;5;N\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 3;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (parts[i + 1] === \"2\" && parts[i + 4] !== undefined) {\n\t\t\t\t\t// RGB color: 38;2;R;G;B or 48;2;R;G;B\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 5;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Standard SGR codes\n\t\t\tswitch (code) {\n\t\t\t\tcase 0:\n\t\t\t\t\tthis.reset();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis.bold = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis.dim = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tthis.italic = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tthis.underline = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tthis.blink = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tthis.inverse = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tthis.hidden = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tthis.strikethrough = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tbreak; // Some terminals\n\t\t\t\tcase 22:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tthis.dim = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tthis.italic = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 24:\n\t\t\t\t\tthis.underline = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tthis.blink = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 27:\n\t\t\t\t\tthis.inverse = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\tthis.hidden = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 29:\n\t\t\t\t\tthis.strikethrough = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\tthis.fgColor = null;\n\t\t\t\t\tbreak; // Default fg\n\t\t\t\tcase 49:\n\t\t\t\t\tthis.bgColor = null;\n\t\t\t\t\tbreak; // Default bg\n\t\t\t\tdefault:\n\t\t\t\t\t// Standard foreground colors 30-37, 90-97\n\t\t\t\t\tif ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {\n\t\t\t\t\t\tthis.fgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\t// Standard background colors 40-47, 100-107\n\t\t\t\t\telse if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {\n\t\t\t\t\t\tthis.bgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\n\tprivate reset(): void {\n\t\tthis.bold = false;\n\t\tthis.dim = false;\n\t\tthis.italic = false;\n\t\tthis.underline = false;\n\t\tthis.blink = false;\n\t\tthis.inverse = false;\n\t\tthis.hidden = false;\n\t\tthis.strikethrough = false;\n\t\tthis.fgColor = null;\n\t\tthis.bgColor = null;\n\t}\n\n\t/** Clear all state for reuse. */\n\tclear(): void {\n\t\tthis.reset();\n\t}\n\n\tgetActiveCodes(): string {\n\t\tconst codes: string[] = [];\n\t\tif (this.bold) codes.push(\"1\");\n\t\tif (this.dim) codes.push(\"2\");\n\t\tif (this.italic) codes.push(\"3\");\n\t\tif (this.underline) codes.push(\"4\");\n\t\tif (this.blink) codes.push(\"5\");\n\t\tif (this.inverse) codes.push(\"7\");\n\t\tif (this.hidden) codes.push(\"8\");\n\t\tif (this.strikethrough) codes.push(\"9\");\n\t\tif (this.fgColor) codes.push(this.fgColor);\n\t\tif (this.bgColor) codes.push(this.bgColor);\n\n\t\tif (codes.length === 0) return \"\";\n\t\treturn `\\x1b[${codes.join(\";\")}m`;\n\t}\n\n\thasActiveCodes(): boolean {\n\t\treturn (\n\t\t\tthis.bold ||\n\t\t\tthis.dim ||\n\t\t\tthis.italic ||\n\t\t\tthis.underline ||\n\t\t\tthis.blink ||\n\t\t\tthis.inverse ||\n\t\t\tthis.hidden ||\n\t\t\tthis.strikethrough ||\n\t\t\tthis.fgColor !== null ||\n\t\t\tthis.bgColor !== null\n\t\t);\n\t}\n\n\t/**\n\t * Get reset codes for attributes that need to be turned off at line end,\n\t * specifically underline which bleeds into padding.\n\t * Returns empty string if no problematic attributes are active.\n\t */\n\tgetLineEndReset(): string {\n\t\t// Only underline causes visual bleeding into padding\n\t\t// Other attributes like colors don't visually bleed to padding\n\t\tif (this.underline) {\n\t\t\treturn \"\\x1b[24m\"; // Underline off only\n\t\t}\n\t\treturn \"\";\n\t}\n}\n\nfunction updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\ttracker.process(ansiResult.code);\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n}\n\n/**\n * Split text into words while keeping ANSI codes attached.\n */\nfunction splitIntoTokensWithAnsi(text: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet pendingAnsi = \"\"; // ANSI codes waiting to be attached to next visible content\n\tlet inWhitespace = false;\n\tlet i = 0;\n\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\t// Hold ANSI codes separately - they'll be attached to the next visible char\n\t\t\tpendingAnsi += ansiResult.code;\n\t\t\ti += ansiResult.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst char = text[i];\n\t\tconst charIsSpace = char === \" \";\n\n\t\tif (charIsSpace !== inWhitespace && current) {\n\t\t\t// Switching between whitespace and non-whitespace, push current token\n\t\t\ttokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t}\n\n\t\t// Attach any pending ANSI codes to this visible character\n\t\tif (pendingAnsi) {\n\t\t\tcurrent += pendingAnsi;\n\t\t\tpendingAnsi = \"\";\n\t\t}\n\n\t\tinWhitespace = charIsSpace;\n\t\tcurrent += char;\n\t\ti++;\n\t}\n\n\t// Handle any remaining pending ANSI codes (attach to last token)\n\tif (pendingAnsi) {\n\t\tcurrent += pendingAnsi;\n\t}\n\n\tif (current) {\n\t\ttokens.push(current);\n\t}\n\n\treturn tokens;\n}\n\n/**\n * Wrap text with ANSI codes preserved.\n *\n * ONLY does word wrapping - NO padding, NO background colors.\n * Returns lines where each line is <= width visible chars.\n * Active ANSI codes are preserved across line breaks.\n *\n * @param text - Text to wrap (may contain ANSI codes and newlines)\n * @param width - Maximum visible width per line\n * @returns Array of wrapped lines (NOT padded to width)\n */\nexport function wrapTextWithAnsi(text: string, width: number): string[] {\n\tif (!text) {\n\t\treturn [\"\"];\n\t}\n\n\t// Handle newlines by processing each line separately\n\t// Track ANSI state across lines so styles carry over after literal newlines\n\tconst inputLines = text.split(\"\\n\");\n\tconst result: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\n\tfor (const inputLine of inputLines) {\n\t\t// Prepend active ANSI codes from previous lines (except for first line)\n\t\tconst prefix = result.length > 0 ? tracker.getActiveCodes() : \"\";\n\t\tresult.push(...wrapSingleLine(prefix + inputLine, width));\n\t\t// Update tracker with codes from this line for next iteration\n\t\tupdateTrackerFromText(inputLine, tracker);\n\t}\n\n\treturn result.length > 0 ? result : [\"\"];\n}\n\nfunction wrapSingleLine(line: string, width: number): string[] {\n\tif (!line) {\n\t\treturn [\"\"];\n\t}\n\n\tconst visibleLength = visibleWidth(line);\n\tif (visibleLength <= width) {\n\t\treturn [line];\n\t}\n\n\tconst wrapped: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\tconst tokens = splitIntoTokensWithAnsi(line);\n\n\tlet currentLine = \"\";\n\tlet currentVisibleLength = 0;\n\n\tfor (const token of tokens) {\n\t\tconst tokenVisibleLength = visibleWidth(token);\n\t\tconst isWhitespace = token.trim() === \"\";\n\n\t\t// Token itself is too long - break it character by character\n\t\tif (tokenVisibleLength > width && !isWhitespace) {\n\t\t\tif (currentLine) {\n\t\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\t\tif (lineEndReset) {\n\t\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t\t}\n\t\t\t\twrapped.push(currentLine);\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t}\n\n\t\t\t// Break long token - breakLongWord handles its own resets\n\t\t\tconst broken = breakLongWord(token, width, tracker);\n\t\t\twrapped.push(...broken.slice(0, -1));\n\t\t\tcurrentLine = broken[broken.length - 1];\n\t\t\tcurrentVisibleLength = visibleWidth(currentLine);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if adding this token would exceed width\n\t\tconst totalNeeded = currentVisibleLength + tokenVisibleLength;\n\n\t\tif (totalNeeded > width && currentVisibleLength > 0) {\n\t\t\t// Trim trailing whitespace, then add underline reset (not full reset, to preserve background)\n\t\t\tlet lineToWrap = currentLine.trimEnd();\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tlineToWrap += lineEndReset;\n\t\t\t}\n\t\t\twrapped.push(lineToWrap);\n\t\t\tif (isWhitespace) {\n\t\t\t\t// Don't start new line with whitespace\n\t\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t} else {\n\t\t\t\tcurrentLine = tracker.getActiveCodes() + token;\n\t\t\t\tcurrentVisibleLength = tokenVisibleLength;\n\t\t\t}\n\t\t} else {\n\t\t\t// Add to current line\n\t\t\tcurrentLine += token;\n\t\t\tcurrentVisibleLength += tokenVisibleLength;\n\t\t}\n\n\t\tupdateTrackerFromText(token, tracker);\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final line - let caller handle it\n\t\twrapped.push(currentLine);\n\t}\n\n\t// Trailing whitespace can cause lines to exceed the requested width\n\treturn wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [\"\"];\n}\n\nconst PUNCTUATION_REGEX = /[(){}[\\]<>.,;:'\"!?+\\-=*/\\\\|&%^$#@~`]/;\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespaceChar(char: string): boolean {\n\treturn /\\s/.test(char);\n}\n\n/**\n * Check if a character is punctuation.\n */\nexport function isPunctuationChar(char: string): boolean {\n\treturn PUNCTUATION_REGEX.test(char);\n}\n\nfunction breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {\n\tconst lines: string[] = [];\n\tlet currentLine = tracker.getActiveCodes();\n\tlet currentWidth = 0;\n\n\t// First, separate ANSI codes from visible content\n\t// We need to handle ANSI codes specially since they're not graphemes\n\tlet i = 0;\n\tconst segments: Array<{ type: \"ansi\" | \"grapheme\"; value: string }> = [];\n\n\twhile (i < word.length) {\n\t\tconst ansiResult = extractAnsiCode(word, i);\n\t\tif (ansiResult) {\n\t\t\tsegments.push({ type: \"ansi\", value: ansiResult.code });\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\t// Find the next ANSI code or end of string\n\t\t\tlet end = i;\n\t\t\twhile (end < word.length) {\n\t\t\t\tconst nextAnsi = extractAnsiCode(word, end);\n\t\t\t\tif (nextAnsi) break;\n\t\t\t\tend++;\n\t\t\t}\n\t\t\t// Segment this non-ANSI portion into graphemes\n\t\t\tconst textPortion = word.slice(i, end);\n\t\t\tfor (const seg of segmenter.segment(textPortion)) {\n\t\t\t\tsegments.push({ type: \"grapheme\", value: seg.segment });\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t}\n\n\t// Now process segments\n\tfor (const seg of segments) {\n\t\tif (seg.type === \"ansi\") {\n\t\t\tcurrentLine += seg.value;\n\t\t\ttracker.process(seg.value);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst grapheme = seg.value;\n\t\t// Skip empty graphemes to avoid issues with string-width calculation\n\t\tif (!grapheme) continue;\n\n\t\tconst graphemeWidth = visibleWidth(grapheme);\n\n\t\tif (currentWidth + graphemeWidth > width) {\n\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t}\n\t\t\tlines.push(currentLine);\n\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\tcurrentWidth = 0;\n\t\t}\n\n\t\tcurrentLine += grapheme;\n\t\tcurrentWidth += graphemeWidth;\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final segment - caller handles continuation\n\t\tlines.push(currentLine);\n\t}\n\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\n/**\n * Apply background color to a line, padding to full width.\n *\n * @param line - Line of text (may contain ANSI codes)\n * @param width - Total width to pad to\n * @param bgFn - Background color function\n * @returns Line with background applied and padded to width\n */\nexport function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string {\n\t// Calculate padding needed\n\tconst visibleLen = visibleWidth(line);\n\tconst paddingNeeded = Math.max(0, width - visibleLen);\n\tconst padding = \" \".repeat(paddingNeeded);\n\n\t// Apply background to content + padding\n\tconst withPadding = line + padding;\n\treturn bgFn(withPadding);\n}\n\n/**\n * Truncate text to fit within a maximum visible width, adding ellipsis if needed.\n * Optionally pad with spaces to reach exactly maxWidth.\n * Properly handles ANSI escape codes (they don't count toward width).\n *\n * @param text - Text to truncate (may contain ANSI codes)\n * @param maxWidth - Maximum visible width\n * @param ellipsis - Ellipsis string to append when truncating (default: \"...\")\n * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)\n * @returns Truncated text, optionally padded to exactly maxWidth\n */\nexport function truncateToWidth(\n\ttext: string,\n\tmaxWidth: number,\n\tellipsis: string = \"...\",\n\tpad: boolean = false,\n): string {\n\tif (maxWidth <= 0) {\n\t\treturn \"\";\n\t}\n\n\tif (text.length === 0) {\n\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t}\n\n\tconst ellipsisWidth = visibleWidth(ellipsis);\n\tif (ellipsisWidth >= maxWidth) {\n\t\tconst textWidth = visibleWidth(text);\n\t\tif (textWidth <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - textWidth) : text;\n\t\t}\n\n\t\tconst clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);\n\t\tif (clippedEllipsis.width === 0) {\n\t\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t\t}\n\t\treturn finalizeTruncatedResult(\"\", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tif (text.length <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - text.length) : text;\n\t\t}\n\t\tconst targetWidth = maxWidth - ellipsisWidth;\n\t\treturn finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n\t}\n\n\tconst targetWidth = maxWidth - ellipsisWidth;\n\tlet result = \"\";\n\tlet pendingAnsi = \"\";\n\tlet visibleSoFar = 0;\n\tlet keptWidth = 0;\n\tlet keepContiguousPrefix = true;\n\tlet overflowed = false;\n\tlet exhaustedInput = false;\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\n\tif (!hasAnsi && !hasTabs) {\n\t\tfor (const { segment } of segmenter.segment(text)) {\n\t\t\tconst width = graphemeWidth(segment);\n\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\tresult += segment;\n\t\t\t\tkeptWidth += width;\n\t\t\t} else {\n\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t}\n\t\t\tvisibleSoFar += width;\n\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\toverflowed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\texhaustedInput = !overflowed;\n\t} else {\n\t\tlet i = 0;\n\t\twhile (i < text.length) {\n\t\t\tconst ansi = extractAnsiCode(text, i);\n\t\t\tif (ansi) {\n\t\t\t\tpendingAnsi += ansi.code;\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (text[i] === \"\\t\") {\n\t\t\t\tif (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += \"\\t\";\n\t\t\t\t\tkeptWidth += 3;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tvisibleSoFar += 3;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet end = i;\n\t\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\t\tif (nextAnsi) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tend++;\n\t\t\t}\n\n\t\t\tfor (const { segment } of segmenter.segment(text.slice(i, end))) {\n\t\t\t\tconst width = graphemeWidth(segment);\n\t\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += segment;\n\t\t\t\t\tkeptWidth += width;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\n\t\t\t\tvisibleSoFar += width;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (overflowed) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t\texhaustedInput = i >= text.length;\n\t}\n\n\tif (!overflowed && exhaustedInput) {\n\t\treturn pad ? text + \" \".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;\n\t}\n\n\treturn finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n}\n\n/**\n * Extract a range of visible columns from a line. Handles ANSI codes and wide chars.\n * @param strict - If true, exclude wide chars at boundary that would extend past the range\n */\nexport function sliceByColumn(line: string, startCol: number, length: number, strict = false): string {\n\treturn sliceWithWidth(line, startCol, length, strict).text;\n}\n\n/** Like sliceByColumn but also returns the actual visible width of the result. */\nexport function sliceWithWidth(\n\tline: string,\n\tstartCol: number,\n\tlength: number,\n\tstrict = false,\n): { text: string; width: number } {\n\tif (length <= 0) return { text: \"\", width: 0 };\n\tconst endCol = startCol + length;\n\tlet result = \"\",\n\t\tresultWidth = 0,\n\t\tcurrentCol = 0,\n\t\ti = 0,\n\t\tpendingAnsi = \"\";\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\tif (currentCol >= startCol && currentCol < endCol) result += ansi.code;\n\t\t\telse if (currentCol < startCol) pendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of segmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tconst inRange = currentCol >= startCol && currentCol < endCol;\n\t\t\tconst fits = !strict || currentCol + w <= endCol;\n\t\t\tif (inRange && fits) {\n\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tresult += segment;\n\t\t\t\tresultWidth += w;\n\t\t\t}\n\t\t\tcurrentCol += w;\n\t\t\tif (currentCol >= endCol) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (currentCol >= endCol) break;\n\t}\n\treturn { text: result, width: resultWidth };\n}\n\n// Pooled tracker instance for extractSegments (avoids allocation per call)\nconst pooledStyleTracker = new AnsiCodeTracker();\n\n/**\n * Extract \"before\" and \"after\" segments from a line in a single pass.\n * Used for overlay compositing where we need content before and after the overlay region.\n * Preserves styling from before the overlay that should affect content after it.\n */\nexport function extractSegments(\n\tline: string,\n\tbeforeEnd: number,\n\tafterStart: number,\n\tafterLen: number,\n\tstrictAfter = false,\n): { before: string; beforeWidth: number; after: string; afterWidth: number } {\n\tlet before = \"\",\n\t\tbeforeWidth = 0,\n\t\tafter = \"\",\n\t\tafterWidth = 0;\n\tlet currentCol = 0,\n\t\ti = 0;\n\tlet pendingAnsiBefore = \"\";\n\tlet afterStarted = false;\n\tconst afterEnd = afterStart + afterLen;\n\n\t// Track styling state so \"after\" inherits styling from before the overlay\n\tpooledStyleTracker.clear();\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\t// Track all SGR codes to know styling state at afterStart\n\t\t\tpooledStyleTracker.process(ansi.code);\n\t\t\t// Include ANSI codes in their respective segments\n\t\t\tif (currentCol < beforeEnd) {\n\t\t\t\tpendingAnsiBefore += ansi.code;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) {\n\t\t\t\t// Only include after we've started \"after\" (styling already prepended)\n\t\t\t\tafter += ansi.code;\n\t\t\t}\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of segmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\n\t\t\tif (currentCol < beforeEnd) {\n\t\t\t\tif (pendingAnsiBefore) {\n\t\t\t\t\tbefore += pendingAnsiBefore;\n\t\t\t\t\tpendingAnsiBefore = \"\";\n\t\t\t\t}\n\t\t\t\tbefore += segment;\n\t\t\t\tbeforeWidth += w;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd) {\n\t\t\t\tconst fits = !strictAfter || currentCol + w <= afterEnd;\n\t\t\t\tif (fits) {\n\t\t\t\t\t// On first \"after\" grapheme, prepend inherited styling from before overlay\n\t\t\t\t\tif (!afterStarted) {\n\t\t\t\t\t\tafter += pooledStyleTracker.getActiveCodes();\n\t\t\t\t\t\tafterStarted = true;\n\t\t\t\t\t}\n\t\t\t\t\tafter += segment;\n\t\t\t\t\tafterWidth += w;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentCol += w;\n\t\t\t// Early exit: done with \"before\" only, or done with both segments\n\t\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t}\n\n\treturn { before, beforeWidth, after, afterWidth };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,wBAAgB,YAAY,IAAI,IAAI,CAAC,SAAS,CAE7C;AAyLD;;GAEG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAuDhD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,G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Q,GACjB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAiE5E","sourcesContent":["import { eastAsianWidth } from \"get-east-asian-width\";\n\n// Grapheme segmenter (shared instance)\nconst segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\n/**\n * Get the shared grapheme segmenter instance.\n */\nexport function getSegmenter(): Intl.Segmenter {\n\treturn segmenter;\n}\n\n/**\n * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji.\n * This is a fast heuristic to avoid the expensive rgiEmojiRegex test.\n * The tested Unicode blocks are deliberately broad to account for future\n * Unicode additions.\n */\nfunction couldBeEmoji(segment: string): boolean {\n\tconst cp = segment.codePointAt(0)!;\n\treturn (\n\t\t(cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph\n\t\t(cp >= 0x2300 && cp <= 0x23ff) || // Misc technical\n\t\t(cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats\n\t\t(cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles\n\t\tsegment.includes(\"\\uFE0F\") || // Contains VS16 (emoji presentation selector)\n\t\tsegment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.)\n\t);\n}\n\n// Regexes for character classification (same as string-width library)\nconst zeroWidthRegex = /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$/v;\nconst leadingNonPrintingRegex = /^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+/v;\nconst rgiEmojiRegex = /^\\p{RGI_Emoji}$/v;\n\n// Cache for non-ASCII strings\nconst WIDTH_CACHE_SIZE = 512;\nconst widthCache = new Map<string, number>();\n\nfunction isPrintableAscii(str: string): boolean {\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst code = str.charCodeAt(i);\n\t\tif (code < 0x20 || code > 0x7e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {\n\tif (maxWidth <= 0 || text.length === 0) {\n\t\treturn { text: \"\", width: 0 };\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tconst clipped = text.slice(0, maxWidth);\n\t\treturn { text: clipped, width: clipped.length };\n\t}\n\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\tif (!hasAnsi && !hasTabs) {\n\t\tlet result = \"\";\n\t\tlet width = 0;\n\t\tfor (const { segment } of segmenter.segment(text)) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\treturn { text: result, width };\n\t}\n\n\tlet result = \"\";\n\tlet width = 0;\n\tlet i = 0;\n\tlet pendingAnsi = \"\";\n\n\twhile (i < text.length) {\n\t\tconst ansi = extractAnsiCode(text, i);\n\t\tif (ansi) {\n\t\t\tpendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (text[i] === \"\\t\") {\n\t\t\tif (width + 3 > maxWidth) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += \"\\t\";\n\t\t\twidth += 3;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet end = i;\n\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\tif (nextAnsi) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tend++;\n\t\t}\n\n\t\tfor (const { segment } of segmenter.segment(text.slice(i, end))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tif (width + w > maxWidth) {\n\t\t\t\treturn { text: result, width };\n\t\t\t}\n\t\t\tif (pendingAnsi) {\n\t\t\t\tresult += pendingAnsi;\n\t\t\t\tpendingAnsi = \"\";\n\t\t\t}\n\t\t\tresult += segment;\n\t\t\twidth += w;\n\t\t}\n\t\ti = end;\n\t}\n\n\treturn { text: result, width };\n}\n\nfunction finalizeTruncatedResult(\n\tprefix: string,\n\tprefixWidth: number,\n\tellipsis: string,\n\tellipsisWidth: number,\n\tmaxWidth: number,\n\tpad: boolean,\n): string {\n\tconst reset = \"\\x1b[0m\";\n\tconst visibleWidth = prefixWidth + ellipsisWidth;\n\tlet result: string;\n\n\tif (ellipsis.length > 0) {\n\t\tresult = `${prefix}${reset}${ellipsis}${reset}`;\n\t} else {\n\t\tresult = `${prefix}${reset}`;\n\t}\n\n\treturn pad ? result + \" \".repeat(Math.max(0, maxWidth - visibleWidth)) : result;\n}\n\n/**\n * Calculate the terminal width of a single grapheme cluster.\n * Based on code from the string-width library, but includes a possible-emoji\n * check to avoid running the RGI_Emoji regex unnecessarily.\n */\nfunction graphemeWidth(segment: string): number {\n\t// Zero-width clusters\n\tif (zeroWidthRegex.test(segment)) {\n\t\treturn 0;\n\t}\n\n\t// Emoji check with pre-filter\n\tif (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {\n\t\treturn 2;\n\t}\n\n\t// Get base visible codepoint\n\tconst base = segment.replace(leadingNonPrintingRegex, \"\");\n\tconst cp = base.codePointAt(0);\n\tif (cp === undefined) {\n\t\treturn 0;\n\t}\n\n\t// Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as\n\t// full-width emoji in terminals, even when isolated during streaming.\n\t// Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.\n\tif (cp >= 0x1f1e6 && cp <= 0x1f1ff) {\n\t\treturn 2;\n\t}\n\n\tlet width = eastAsianWidth(cp);\n\n\t// Trailing halfwidth/fullwidth forms\n\tif (segment.length > 1) {\n\t\tfor (const char of segment.slice(1)) {\n\t\t\tconst c = char.codePointAt(0)!;\n\t\t\tif (c >= 0xff00 && c <= 0xffef) {\n\t\t\t\twidth += eastAsianWidth(c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn width;\n}\n\n/**\n * Calculate the visible width of a string in terminal columns.\n */\nexport function visibleWidth(str: string): number {\n\tif (str.length === 0) {\n\t\treturn 0;\n\t}\n\n\t// Fast path: pure ASCII printable\n\tif (isPrintableAscii(str)) {\n\t\treturn str.length;\n\t}\n\n\t// Check cache\n\tconst cached = widthCache.get(str);\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Normalize: tabs to 3 spaces, strip ANSI escape codes\n\tlet clean = str;\n\tif (str.includes(\"\\t\")) {\n\t\tclean = clean.replace(/\\t/g, \" \");\n\t}\n\tif (clean.includes(\"\\x1b\")) {\n\t\t// Strip supported ANSI/OSC/APC escape sequences in one pass.\n\t\t// This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,\n\t\t// and APC sequences like CURSOR_MARKER.\n\t\tlet stripped = \"\";\n\t\tlet i = 0;\n\t\twhile (i < clean.length) {\n\t\t\tconst ansi = extractAnsiCode(clean, i);\n\t\t\tif (ansi) {\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstripped += clean[i];\n\t\t\ti++;\n\t\t}\n\t\tclean = stripped;\n\t}\n\n\t// Calculate width\n\tlet width = 0;\n\tfor (const { segment } of segmenter.segment(clean)) {\n\t\twidth += graphemeWidth(segment);\n\t}\n\n\t// Cache result\n\tif (widthCache.size >= WIDTH_CACHE_SIZE) {\n\t\tconst firstKey = widthCache.keys().next().value;\n\t\tif (firstKey !== undefined) {\n\t\t\twidthCache.delete(firstKey);\n\t\t}\n\t}\n\twidthCache.set(str, width);\n\n\treturn width;\n}\n\n/**\n * Extract ANSI escape sequences from a string at the given position.\n */\nexport function extractAnsiCode(str: string, pos: number): { code: string; length: number } | null {\n\tif (pos >= str.length || str[pos] !== \"\\x1b\") return null;\n\n\tconst next = str[pos + 1];\n\n\t// CSI sequence: ESC [ ... m/G/K/H/J\n\tif (next === \"[\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;\n\t\tif (j < str.length) return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\treturn null;\n\t}\n\n\t// OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \\)\n\t// Used for hyperlinks (OSC 8), window titles, etc.\n\tif (next === \"]\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\t// APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \\)\n\t// Used for cursor marker and application-specific commands\n\tif (next === \"_\") {\n\t\tlet j = pos + 2;\n\t\twhile (j < str.length) {\n\t\t\tif (str[j] === \"\\x07\") return { code: str.substring(pos, j + 1), length: j + 1 - pos };\n\t\t\tif (str[j] === \"\\x1b\" && str[j + 1] === \"\\\\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };\n\t\t\tj++;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn null;\n}\n\n/**\n * Track active ANSI SGR codes to preserve styling across line breaks.\n */\nclass AnsiCodeTracker {\n\t// Track individual attributes separately so we can reset them specifically\n\tprivate bold = false;\n\tprivate dim = false;\n\tprivate italic = false;\n\tprivate underline = false;\n\tprivate blink = false;\n\tprivate inverse = false;\n\tprivate hidden = false;\n\tprivate strikethrough = false;\n\tprivate fgColor: string | null = null; // Stores the full code like \"31\" or \"38;5;240\"\n\tprivate bgColor: string | null = null; // Stores the full code like \"41\" or \"48;5;240\"\n\tprivate activeHyperlink: string | null = null; // Active OSC 8 hyperlink URL, or null\n\n\tprocess(ansiCode: string): void {\n\t\t// OSC 8 hyperlink: \\x1b]8;;<url>\\x1b\\\\ (open) or \\x1b]8;;\\x1b\\\\ (close)\n\t\tif (ansiCode.startsWith(\"\\x1b]8;\")) {\n\t\t\tconst m = ansiCode.match(/^\\x1b\\]8;[^;]*;([^\\x1b\\x07]*)/);\n\t\t\tthis.activeHyperlink = m?.[1] ? m[1] : null;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ansiCode.endsWith(\"m\")) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Extract the parameters between \\x1b[ and m\n\t\tconst match = ansiCode.match(/\\x1b\\[([\\d;]*)m/);\n\t\tif (!match) return;\n\n\t\tconst params = match[1];\n\t\tif (params === \"\" || params === \"0\") {\n\t\t\t// Full reset\n\t\t\tthis.reset();\n\t\t\treturn;\n\t\t}\n\n\t\t// Parse parameters (can be semicolon-separated)\n\t\tconst parts = params.split(\";\");\n\t\tlet i = 0;\n\t\twhile (i < parts.length) {\n\t\t\tconst code = Number.parseInt(parts[i], 10);\n\n\t\t\t// Handle 256-color and RGB codes which consume multiple parameters\n\t\t\tif (code === 38 || code === 48) {\n\t\t\t\t// 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg)\n\t\t\t\t// 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg)\n\t\t\t\tif (parts[i + 1] === \"5\" && parts[i + 2] !== undefined) {\n\t\t\t\t\t// 256 color: 38;5;N or 48;5;N\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 3;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (parts[i + 1] === \"2\" && parts[i + 4] !== undefined) {\n\t\t\t\t\t// RGB color: 38;2;R;G;B or 48;2;R;G;B\n\t\t\t\t\tconst colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;\n\t\t\t\t\tif (code === 38) {\n\t\t\t\t\t\tthis.fgColor = colorCode;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.bgColor = colorCode;\n\t\t\t\t\t}\n\t\t\t\t\ti += 5;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Standard SGR codes\n\t\t\tswitch (code) {\n\t\t\t\tcase 0:\n\t\t\t\t\tthis.reset();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis.bold = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis.dim = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tthis.italic = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tthis.underline = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tthis.blink = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tthis.inverse = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tthis.hidden = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tthis.strikethrough = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tbreak; // Some terminals\n\t\t\t\tcase 22:\n\t\t\t\t\tthis.bold = false;\n\t\t\t\t\tthis.dim = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tthis.italic = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 24:\n\t\t\t\t\tthis.underline = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tthis.blink = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 27:\n\t\t\t\t\tthis.inverse = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\tthis.hidden = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 29:\n\t\t\t\t\tthis.strikethrough = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\tthis.fgColor = null;\n\t\t\t\t\tbreak; // Default fg\n\t\t\t\tcase 49:\n\t\t\t\t\tthis.bgColor = null;\n\t\t\t\t\tbreak; // Default bg\n\t\t\t\tdefault:\n\t\t\t\t\t// Standard foreground colors 30-37, 90-97\n\t\t\t\t\tif ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {\n\t\t\t\t\t\tthis.fgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\t// Standard background colors 40-47, 100-107\n\t\t\t\t\telse if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {\n\t\t\t\t\t\tthis.bgColor = String(code);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\n\tprivate reset(): void {\n\t\tthis.bold = false;\n\t\tthis.dim = false;\n\t\tthis.italic = false;\n\t\tthis.underline = false;\n\t\tthis.blink = false;\n\t\tthis.inverse = false;\n\t\tthis.hidden = false;\n\t\tthis.strikethrough = false;\n\t\tthis.fgColor = null;\n\t\tthis.bgColor = null;\n\t\t// SGR reset does not affect OSC 8 hyperlink state\n\t}\n\n\t/** Clear all state for reuse. */\n\tclear(): void {\n\t\tthis.reset();\n\t\tthis.activeHyperlink = null;\n\t}\n\n\tgetActiveCodes(): string {\n\t\tconst codes: string[] = [];\n\t\tif (this.bold) codes.push(\"1\");\n\t\tif (this.dim) codes.push(\"2\");\n\t\tif (this.italic) codes.push(\"3\");\n\t\tif (this.underline) codes.push(\"4\");\n\t\tif (this.blink) codes.push(\"5\");\n\t\tif (this.inverse) codes.push(\"7\");\n\t\tif (this.hidden) codes.push(\"8\");\n\t\tif (this.strikethrough) codes.push(\"9\");\n\t\tif (this.fgColor) codes.push(this.fgColor);\n\t\tif (this.bgColor) codes.push(this.bgColor);\n\n\t\tlet result = codes.length > 0 ? `\\x1b[${codes.join(\";\")}m` : \"\";\n\t\tif (this.activeHyperlink) {\n\t\t\tresult += `\\x1b]8;;${this.activeHyperlink}\\x1b\\\\`;\n\t\t}\n\t\treturn result;\n\t}\n\n\thasActiveCodes(): boolean {\n\t\treturn (\n\t\t\tthis.bold ||\n\t\t\tthis.dim ||\n\t\t\tthis.italic ||\n\t\t\tthis.underline ||\n\t\t\tthis.blink ||\n\t\t\tthis.inverse ||\n\t\t\tthis.hidden ||\n\t\t\tthis.strikethrough ||\n\t\t\tthis.fgColor !== null ||\n\t\t\tthis.bgColor !== null ||\n\t\t\tthis.activeHyperlink !== null\n\t\t);\n\t}\n\n\t/**\n\t * Get reset codes for attributes that need to be turned off at line end.\n\t * Underline must be closed to prevent bleeding into padding.\n\t * Active OSC 8 hyperlinks must be closed and re-opened on the next line.\n\t * Returns empty string if no attributes need closing.\n\t */\n\tgetLineEndReset(): string {\n\t\tlet result = \"\";\n\t\tif (this.underline) {\n\t\t\tresult += \"\\x1b[24m\"; // Underline off only\n\t\t}\n\t\tif (this.activeHyperlink) {\n\t\t\tresult += \"\\x1b]8;;\\x1b\\\\\"; // Close hyperlink; re-opened at line start via getActiveCodes()\n\t\t}\n\t\treturn result;\n\t}\n}\n\nfunction updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\ttracker.process(ansiResult.code);\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n}\n\n/**\n * Split text into words while keeping ANSI codes attached.\n */\nfunction splitIntoTokensWithAnsi(text: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet pendingAnsi = \"\"; // ANSI codes waiting to be attached to next visible content\n\tlet inWhitespace = false;\n\tlet i = 0;\n\n\twhile (i < text.length) {\n\t\tconst ansiResult = extractAnsiCode(text, i);\n\t\tif (ansiResult) {\n\t\t\t// Hold ANSI codes separately - they'll be attached to the next visible char\n\t\t\tpendingAnsi += ansiResult.code;\n\t\t\ti += ansiResult.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst char = text[i];\n\t\tconst charIsSpace = char === \" \";\n\n\t\tif (charIsSpace !== inWhitespace && current) {\n\t\t\t// Switching between whitespace and non-whitespace, push current token\n\t\t\ttokens.push(current);\n\t\t\tcurrent = \"\";\n\t\t}\n\n\t\t// Attach any pending ANSI codes to this visible character\n\t\tif (pendingAnsi) {\n\t\t\tcurrent += pendingAnsi;\n\t\t\tpendingAnsi = \"\";\n\t\t}\n\n\t\tinWhitespace = charIsSpace;\n\t\tcurrent += char;\n\t\ti++;\n\t}\n\n\t// Handle any remaining pending ANSI codes (attach to last token)\n\tif (pendingAnsi) {\n\t\tcurrent += pendingAnsi;\n\t}\n\n\tif (current) {\n\t\ttokens.push(current);\n\t}\n\n\treturn tokens;\n}\n\n/**\n * Wrap text with ANSI codes preserved.\n *\n * ONLY does word wrapping - NO padding, NO background colors.\n * Returns lines where each line is <= width visible chars.\n * Active ANSI codes are preserved across line breaks.\n *\n * @param text - Text to wrap (may contain ANSI codes and newlines)\n * @param width - Maximum visible width per line\n * @returns Array of wrapped lines (NOT padded to width)\n */\nexport function wrapTextWithAnsi(text: string, width: number): string[] {\n\tif (!text) {\n\t\treturn [\"\"];\n\t}\n\n\t// Handle newlines by processing each line separately\n\t// Track ANSI state across lines so styles carry over after literal newlines\n\tconst inputLines = text.split(\"\\n\");\n\tconst result: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\n\tfor (const inputLine of inputLines) {\n\t\t// Prepend active ANSI codes from previous lines (except for first line)\n\t\tconst prefix = result.length > 0 ? tracker.getActiveCodes() : \"\";\n\t\tresult.push(...wrapSingleLine(prefix + inputLine, width));\n\t\t// Update tracker with codes from this line for next iteration\n\t\tupdateTrackerFromText(inputLine, tracker);\n\t}\n\n\treturn result.length > 0 ? result : [\"\"];\n}\n\nfunction wrapSingleLine(line: string, width: number): string[] {\n\tif (!line) {\n\t\treturn [\"\"];\n\t}\n\n\tconst visibleLength = visibleWidth(line);\n\tif (visibleLength <= width) {\n\t\treturn [line];\n\t}\n\n\tconst wrapped: string[] = [];\n\tconst tracker = new AnsiCodeTracker();\n\tconst tokens = splitIntoTokensWithAnsi(line);\n\n\tlet currentLine = \"\";\n\tlet currentVisibleLength = 0;\n\n\tfor (const token of tokens) {\n\t\tconst tokenVisibleLength = visibleWidth(token);\n\t\tconst isWhitespace = token.trim() === \"\";\n\n\t\t// Token itself is too long - break it character by character\n\t\tif (tokenVisibleLength > width && !isWhitespace) {\n\t\t\tif (currentLine) {\n\t\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\t\tif (lineEndReset) {\n\t\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t\t}\n\t\t\t\twrapped.push(currentLine);\n\t\t\t\tcurrentLine = \"\";\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t}\n\n\t\t\t// Break long token - breakLongWord handles its own resets\n\t\t\tconst broken = breakLongWord(token, width, tracker);\n\t\t\twrapped.push(...broken.slice(0, -1));\n\t\t\tcurrentLine = broken[broken.length - 1];\n\t\t\tcurrentVisibleLength = visibleWidth(currentLine);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if adding this token would exceed width\n\t\tconst totalNeeded = currentVisibleLength + tokenVisibleLength;\n\n\t\tif (totalNeeded > width && currentVisibleLength > 0) {\n\t\t\t// Trim trailing whitespace, then add underline reset (not full reset, to preserve background)\n\t\t\tlet lineToWrap = currentLine.trimEnd();\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tlineToWrap += lineEndReset;\n\t\t\t}\n\t\t\twrapped.push(lineToWrap);\n\t\t\tif (isWhitespace) {\n\t\t\t\t// Don't start new line with whitespace\n\t\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\t\tcurrentVisibleLength = 0;\n\t\t\t} else {\n\t\t\t\tcurrentLine = tracker.getActiveCodes() + token;\n\t\t\t\tcurrentVisibleLength = tokenVisibleLength;\n\t\t\t}\n\t\t} else {\n\t\t\t// Add to current line\n\t\t\tcurrentLine += token;\n\t\t\tcurrentVisibleLength += tokenVisibleLength;\n\t\t}\n\n\t\tupdateTrackerFromText(token, tracker);\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final line - let caller handle it\n\t\twrapped.push(currentLine);\n\t}\n\n\t// Trailing whitespace can cause lines to exceed the requested width\n\treturn wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [\"\"];\n}\n\nconst PUNCTUATION_REGEX = /[(){}[\\]<>.,;:'\"!?+\\-=*/\\\\|&%^$#@~`]/;\n\n/**\n * Check if a character is whitespace.\n */\nexport function isWhitespaceChar(char: string): boolean {\n\treturn /\\s/.test(char);\n}\n\n/**\n * Check if a character is punctuation.\n */\nexport function isPunctuationChar(char: string): boolean {\n\treturn PUNCTUATION_REGEX.test(char);\n}\n\nfunction breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {\n\tconst lines: string[] = [];\n\tlet currentLine = tracker.getActiveCodes();\n\tlet currentWidth = 0;\n\n\t// First, separate ANSI codes from visible content\n\t// We need to handle ANSI codes specially since they're not graphemes\n\tlet i = 0;\n\tconst segments: Array<{ type: \"ansi\" | \"grapheme\"; value: string }> = [];\n\n\twhile (i < word.length) {\n\t\tconst ansiResult = extractAnsiCode(word, i);\n\t\tif (ansiResult) {\n\t\t\tsegments.push({ type: \"ansi\", value: ansiResult.code });\n\t\t\ti += ansiResult.length;\n\t\t} else {\n\t\t\t// Find the next ANSI code or end of string\n\t\t\tlet end = i;\n\t\t\twhile (end < word.length) {\n\t\t\t\tconst nextAnsi = extractAnsiCode(word, end);\n\t\t\t\tif (nextAnsi) break;\n\t\t\t\tend++;\n\t\t\t}\n\t\t\t// Segment this non-ANSI portion into graphemes\n\t\t\tconst textPortion = word.slice(i, end);\n\t\t\tfor (const seg of segmenter.segment(textPortion)) {\n\t\t\t\tsegments.push({ type: \"grapheme\", value: seg.segment });\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t}\n\n\t// Now process segments\n\tfor (const seg of segments) {\n\t\tif (seg.type === \"ansi\") {\n\t\t\tcurrentLine += seg.value;\n\t\t\ttracker.process(seg.value);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst grapheme = seg.value;\n\t\t// Skip empty graphemes to avoid issues with string-width calculation\n\t\tif (!grapheme) continue;\n\n\t\tconst graphemeWidth = visibleWidth(grapheme);\n\n\t\tif (currentWidth + graphemeWidth > width) {\n\t\t\t// Add specific reset for underline only (preserves background)\n\t\t\tconst lineEndReset = tracker.getLineEndReset();\n\t\t\tif (lineEndReset) {\n\t\t\t\tcurrentLine += lineEndReset;\n\t\t\t}\n\t\t\tlines.push(currentLine);\n\t\t\tcurrentLine = tracker.getActiveCodes();\n\t\t\tcurrentWidth = 0;\n\t\t}\n\n\t\tcurrentLine += grapheme;\n\t\tcurrentWidth += graphemeWidth;\n\t}\n\n\tif (currentLine) {\n\t\t// No reset at end of final segment - caller handles continuation\n\t\tlines.push(currentLine);\n\t}\n\n\treturn lines.length > 0 ? lines : [\"\"];\n}\n\n/**\n * Apply background color to a line, padding to full width.\n *\n * @param line - Line of text (may contain ANSI codes)\n * @param width - Total width to pad to\n * @param bgFn - Background color function\n * @returns Line with background applied and padded to width\n */\nexport function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string {\n\t// Calculate padding needed\n\tconst visibleLen = visibleWidth(line);\n\tconst paddingNeeded = Math.max(0, width - visibleLen);\n\tconst padding = \" \".repeat(paddingNeeded);\n\n\t// Apply background to content + padding\n\tconst withPadding = line + padding;\n\treturn bgFn(withPadding);\n}\n\n/**\n * Truncate text to fit within a maximum visible width, adding ellipsis if needed.\n * Optionally pad with spaces to reach exactly maxWidth.\n * Properly handles ANSI escape codes (they don't count toward width).\n *\n * @param text - Text to truncate (may contain ANSI codes)\n * @param maxWidth - Maximum visible width\n * @param ellipsis - Ellipsis string to append when truncating (default: \"...\")\n * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)\n * @returns Truncated text, optionally padded to exactly maxWidth\n */\nexport function truncateToWidth(\n\ttext: string,\n\tmaxWidth: number,\n\tellipsis: string = \"...\",\n\tpad: boolean = false,\n): string {\n\tif (maxWidth <= 0) {\n\t\treturn \"\";\n\t}\n\n\tif (text.length === 0) {\n\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t}\n\n\tconst ellipsisWidth = visibleWidth(ellipsis);\n\tif (ellipsisWidth >= maxWidth) {\n\t\tconst textWidth = visibleWidth(text);\n\t\tif (textWidth <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - textWidth) : text;\n\t\t}\n\n\t\tconst clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);\n\t\tif (clippedEllipsis.width === 0) {\n\t\t\treturn pad ? \" \".repeat(maxWidth) : \"\";\n\t\t}\n\t\treturn finalizeTruncatedResult(\"\", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);\n\t}\n\n\tif (isPrintableAscii(text)) {\n\t\tif (text.length <= maxWidth) {\n\t\t\treturn pad ? text + \" \".repeat(maxWidth - text.length) : text;\n\t\t}\n\t\tconst targetWidth = maxWidth - ellipsisWidth;\n\t\treturn finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n\t}\n\n\tconst targetWidth = maxWidth - ellipsisWidth;\n\tlet result = \"\";\n\tlet pendingAnsi = \"\";\n\tlet visibleSoFar = 0;\n\tlet keptWidth = 0;\n\tlet keepContiguousPrefix = true;\n\tlet overflowed = false;\n\tlet exhaustedInput = false;\n\tconst hasAnsi = text.includes(\"\\x1b\");\n\tconst hasTabs = text.includes(\"\\t\");\n\n\tif (!hasAnsi && !hasTabs) {\n\t\tfor (const { segment } of segmenter.segment(text)) {\n\t\t\tconst width = graphemeWidth(segment);\n\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\tresult += segment;\n\t\t\t\tkeptWidth += width;\n\t\t\t} else {\n\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t}\n\t\t\tvisibleSoFar += width;\n\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\toverflowed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\texhaustedInput = !overflowed;\n\t} else {\n\t\tlet i = 0;\n\t\twhile (i < text.length) {\n\t\t\tconst ansi = extractAnsiCode(text, i);\n\t\t\tif (ansi) {\n\t\t\t\tpendingAnsi += ansi.code;\n\t\t\t\ti += ansi.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (text[i] === \"\\t\") {\n\t\t\t\tif (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += \"\\t\";\n\t\t\t\t\tkeptWidth += 3;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tvisibleSoFar += 3;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet end = i;\n\t\t\twhile (end < text.length && text[end] !== \"\\t\") {\n\t\t\t\tconst nextAnsi = extractAnsiCode(text, end);\n\t\t\t\tif (nextAnsi) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tend++;\n\t\t\t}\n\n\t\t\tfor (const { segment } of segmenter.segment(text.slice(i, end))) {\n\t\t\t\tconst width = graphemeWidth(segment);\n\t\t\t\tif (keepContiguousPrefix && keptWidth + width <= targetWidth) {\n\t\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tresult += segment;\n\t\t\t\t\tkeptWidth += width;\n\t\t\t\t} else {\n\t\t\t\t\tkeepContiguousPrefix = false;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\n\t\t\t\tvisibleSoFar += width;\n\t\t\t\tif (visibleSoFar > maxWidth) {\n\t\t\t\t\toverflowed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (overflowed) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti = end;\n\t\t}\n\t\texhaustedInput = i >= text.length;\n\t}\n\n\tif (!overflowed && exhaustedInput) {\n\t\treturn pad ? text + \" \".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;\n\t}\n\n\treturn finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);\n}\n\n/**\n * Extract a range of visible columns from a line. Handles ANSI codes and wide chars.\n * @param strict - If true, exclude wide chars at boundary that would extend past the range\n */\nexport function sliceByColumn(line: string, startCol: number, length: number, strict = false): string {\n\treturn sliceWithWidth(line, startCol, length, strict).text;\n}\n\n/** Like sliceByColumn but also returns the actual visible width of the result. */\nexport function sliceWithWidth(\n\tline: string,\n\tstartCol: number,\n\tlength: number,\n\tstrict = false,\n): { text: string; width: number } {\n\tif (length <= 0) return { text: \"\", width: 0 };\n\tconst endCol = startCol + length;\n\tlet result = \"\",\n\t\tresultWidth = 0,\n\t\tcurrentCol = 0,\n\t\ti = 0,\n\t\tpendingAnsi = \"\";\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\tif (currentCol >= startCol && currentCol < endCol) result += ansi.code;\n\t\t\telse if (currentCol < startCol) pendingAnsi += ansi.code;\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of segmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\t\t\tconst inRange = currentCol >= startCol && currentCol < endCol;\n\t\t\tconst fits = !strict || currentCol + w <= endCol;\n\t\t\tif (inRange && fits) {\n\t\t\t\tif (pendingAnsi) {\n\t\t\t\t\tresult += pendingAnsi;\n\t\t\t\t\tpendingAnsi = \"\";\n\t\t\t\t}\n\t\t\t\tresult += segment;\n\t\t\t\tresultWidth += w;\n\t\t\t}\n\t\t\tcurrentCol += w;\n\t\t\tif (currentCol >= endCol) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (currentCol >= endCol) break;\n\t}\n\treturn { text: result, width: resultWidth };\n}\n\n// Pooled tracker instance for extractSegments (avoids allocation per call)\nconst pooledStyleTracker = new AnsiCodeTracker();\n\n/**\n * Extract \"before\" and \"after\" segments from a line in a single pass.\n * Used for overlay compositing where we need content before and after the overlay region.\n * Preserves styling from before the overlay that should affect content after it.\n */\nexport function extractSegments(\n\tline: string,\n\tbeforeEnd: number,\n\tafterStart: number,\n\tafterLen: number,\n\tstrictAfter = false,\n): { before: string; beforeWidth: number; after: string; afterWidth: number } {\n\tlet before = \"\",\n\t\tbeforeWidth = 0,\n\t\tafter = \"\",\n\t\tafterWidth = 0;\n\tlet currentCol = 0,\n\t\ti = 0;\n\tlet pendingAnsiBefore = \"\";\n\tlet afterStarted = false;\n\tconst afterEnd = afterStart + afterLen;\n\n\t// Track styling state so \"after\" inherits styling from before the overlay\n\tpooledStyleTracker.clear();\n\n\twhile (i < line.length) {\n\t\tconst ansi = extractAnsiCode(line, i);\n\t\tif (ansi) {\n\t\t\t// Track all SGR codes to know styling state at afterStart\n\t\t\tpooledStyleTracker.process(ansi.code);\n\t\t\t// Include ANSI codes in their respective segments\n\t\t\tif (currentCol < beforeEnd) {\n\t\t\t\tpendingAnsiBefore += ansi.code;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) {\n\t\t\t\t// Only include after we've started \"after\" (styling already prepended)\n\t\t\t\tafter += ansi.code;\n\t\t\t}\n\t\t\ti += ansi.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet textEnd = i;\n\t\twhile (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;\n\n\t\tfor (const { segment } of segmenter.segment(line.slice(i, textEnd))) {\n\t\t\tconst w = graphemeWidth(segment);\n\n\t\t\tif (currentCol < beforeEnd) {\n\t\t\t\tif (pendingAnsiBefore) {\n\t\t\t\t\tbefore += pendingAnsiBefore;\n\t\t\t\t\tpendingAnsiBefore = \"\";\n\t\t\t\t}\n\t\t\t\tbefore += segment;\n\t\t\t\tbeforeWidth += w;\n\t\t\t} else if (currentCol >= afterStart && currentCol < afterEnd) {\n\t\t\t\tconst fits = !strictAfter || currentCol + w <= afterEnd;\n\t\t\t\tif (fits) {\n\t\t\t\t\t// On first \"after\" grapheme, prepend inherited styling from before overlay\n\t\t\t\t\tif (!afterStarted) {\n\t\t\t\t\t\tafter += pooledStyleTracker.getActiveCodes();\n\t\t\t\t\t\tafterStarted = true;\n\t\t\t\t\t}\n\t\t\t\t\tafter += segment;\n\t\t\t\t\tafterWidth += w;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentCol += w;\n\t\t\t// Early exit: done with \"before\" only, or done with both segments\n\t\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t\t}\n\t\ti = textEnd;\n\t\tif (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;\n\t}\n\n\treturn { before, beforeWidth, after, afterWidth };\n}\n"]}
|
package/dist/utils.js
CHANGED
|
@@ -272,7 +272,14 @@ class AnsiCodeTracker {
|
|
|
272
272
|
strikethrough = false;
|
|
273
273
|
fgColor = null; // Stores the full code like "31" or "38;5;240"
|
|
274
274
|
bgColor = null; // Stores the full code like "41" or "48;5;240"
|
|
275
|
+
activeHyperlink = null; // Active OSC 8 hyperlink URL, or null
|
|
275
276
|
process(ansiCode) {
|
|
277
|
+
// OSC 8 hyperlink: \x1b]8;;<url>\x1b\\ (open) or \x1b]8;;\x1b\\ (close)
|
|
278
|
+
if (ansiCode.startsWith("\x1b]8;")) {
|
|
279
|
+
const m = ansiCode.match(/^\x1b\]8;[^;]*;([^\x1b\x07]*)/);
|
|
280
|
+
this.activeHyperlink = m?.[1] ? m[1] : null;
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
276
283
|
if (!ansiCode.endsWith("m")) {
|
|
277
284
|
return;
|
|
278
285
|
}
|
|
@@ -405,10 +412,12 @@ class AnsiCodeTracker {
|
|
|
405
412
|
this.strikethrough = false;
|
|
406
413
|
this.fgColor = null;
|
|
407
414
|
this.bgColor = null;
|
|
415
|
+
// SGR reset does not affect OSC 8 hyperlink state
|
|
408
416
|
}
|
|
409
417
|
/** Clear all state for reuse. */
|
|
410
418
|
clear() {
|
|
411
419
|
this.reset();
|
|
420
|
+
this.activeHyperlink = null;
|
|
412
421
|
}
|
|
413
422
|
getActiveCodes() {
|
|
414
423
|
const codes = [];
|
|
@@ -432,9 +441,11 @@ class AnsiCodeTracker {
|
|
|
432
441
|
codes.push(this.fgColor);
|
|
433
442
|
if (this.bgColor)
|
|
434
443
|
codes.push(this.bgColor);
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
444
|
+
let result = codes.length > 0 ? `\x1b[${codes.join(";")}m` : "";
|
|
445
|
+
if (this.activeHyperlink) {
|
|
446
|
+
result += `\x1b]8;;${this.activeHyperlink}\x1b\\`;
|
|
447
|
+
}
|
|
448
|
+
return result;
|
|
438
449
|
}
|
|
439
450
|
hasActiveCodes() {
|
|
440
451
|
return (this.bold ||
|
|
@@ -446,20 +457,24 @@ class AnsiCodeTracker {
|
|
|
446
457
|
this.hidden ||
|
|
447
458
|
this.strikethrough ||
|
|
448
459
|
this.fgColor !== null ||
|
|
449
|
-
this.bgColor !== null
|
|
460
|
+
this.bgColor !== null ||
|
|
461
|
+
this.activeHyperlink !== null);
|
|
450
462
|
}
|
|
451
463
|
/**
|
|
452
|
-
* Get reset codes for attributes that need to be turned off at line end
|
|
453
|
-
*
|
|
454
|
-
*
|
|
464
|
+
* Get reset codes for attributes that need to be turned off at line end.
|
|
465
|
+
* Underline must be closed to prevent bleeding into padding.
|
|
466
|
+
* Active OSC 8 hyperlinks must be closed and re-opened on the next line.
|
|
467
|
+
* Returns empty string if no attributes need closing.
|
|
455
468
|
*/
|
|
456
469
|
getLineEndReset() {
|
|
457
|
-
|
|
458
|
-
// Other attributes like colors don't visually bleed to padding
|
|
470
|
+
let result = "";
|
|
459
471
|
if (this.underline) {
|
|
460
|
-
|
|
472
|
+
result += "\x1b[24m"; // Underline off only
|
|
461
473
|
}
|
|
462
|
-
|
|
474
|
+
if (this.activeHyperlink) {
|
|
475
|
+
result += "\x1b]8;;\x1b\\"; // Close hyperlink; re-opened at line start via getActiveCodes()
|
|
476
|
+
}
|
|
477
|
+
return result;
|
|
463
478
|
}
|
|
464
479
|
}
|
|
465
480
|
function updateTrackerFromText(text, tracker) {
|