@xincli/opentui-core 0.4.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.
Files changed (476) hide show
  1. package/README.md +63 -0
  2. package/dev/keypress-debug-renderer.ts +148 -0
  3. package/dev/keypress-debug.ts +43 -0
  4. package/dev/print-env-vars.ts +32 -0
  5. package/dev/test-tmux-graphics-334.sh +68 -0
  6. package/dev/test-tmux-theme-queries.sh +151 -0
  7. package/dev/thai-debug-test.ts +68 -0
  8. package/dev/theme-mode.ts +290 -0
  9. package/docs/development.md +144 -0
  10. package/package.json +102 -0
  11. package/prebuilt/aarch64-android/libopentui.so +0 -0
  12. package/scripts/build-android.ts +226 -0
  13. package/scripts/build-native-termux.sh +525 -0
  14. package/scripts/build.ts +530 -0
  15. package/scripts/dist-test.ts +312 -0
  16. package/scripts/package-prebuilt.ts +110 -0
  17. package/scripts/publish.ts +60 -0
  18. package/scripts/test-node-hook.mjs +16 -0
  19. package/scripts/test-node.ts +241 -0
  20. package/scripts/vendor-deps.sh +73 -0
  21. package/src/NativeSpanFeed.ts +375 -0
  22. package/src/Renderable.ts +1878 -0
  23. package/src/__snapshots__/buffer.test.ts.snap +28 -0
  24. package/src/animation/Timeline.test.ts +2709 -0
  25. package/src/animation/Timeline.ts +598 -0
  26. package/src/ansi.ts +22 -0
  27. package/src/audio.ts +479 -0
  28. package/src/benchmark/attenuation-benchmark.ts +81 -0
  29. package/src/benchmark/audio-playback-benchmark.ts +344 -0
  30. package/src/benchmark/box-draw-benchmark.ts +1042 -0
  31. package/src/benchmark/colormatrix-benchmark.ts +123 -0
  32. package/src/benchmark/gain-benchmark.ts +80 -0
  33. package/src/benchmark/latest-all-bench-run.json +707 -0
  34. package/src/benchmark/latest-async-bench-run.json +336 -0
  35. package/src/benchmark/latest-default-bench-run.json +657 -0
  36. package/src/benchmark/latest-large-bench-run.json +707 -0
  37. package/src/benchmark/latest-quick-bench-run.json +207 -0
  38. package/src/benchmark/layout-benchmark.ts +2547 -0
  39. package/src/benchmark/markdown-benchmark.ts +1796 -0
  40. package/src/benchmark/native-span-feed-async-benchmark.ts +355 -0
  41. package/src/benchmark/native-span-feed-benchmark.md +56 -0
  42. package/src/benchmark/native-span-feed-benchmark.ts +596 -0
  43. package/src/benchmark/native-span-feed-compare.ts +280 -0
  44. package/src/benchmark/render-traversal-benchmark.ts +928 -0
  45. package/src/benchmark/text-buffer-render-benchmark.ts +874 -0
  46. package/src/benchmark/text-table-benchmark.ts +948 -0
  47. package/src/buffer.test.ts +292 -0
  48. package/src/buffer.ts +564 -0
  49. package/src/console.test.ts +629 -0
  50. package/src/console.ts +1253 -0
  51. package/src/edit-buffer.test.ts +1852 -0
  52. package/src/edit-buffer.ts +417 -0
  53. package/src/editor-view.test.ts +1056 -0
  54. package/src/editor-view.ts +290 -0
  55. package/src/index.ts +25 -0
  56. package/src/lib/KeyHandler.integration.test.ts +292 -0
  57. package/src/lib/KeyHandler.stopPropagation.test.ts +289 -0
  58. package/src/lib/KeyHandler.test.ts +662 -0
  59. package/src/lib/KeyHandler.ts +222 -0
  60. package/src/lib/RGBA.test.ts +60 -0
  61. package/src/lib/RGBA.ts +343 -0
  62. package/src/lib/ascii.font.ts +330 -0
  63. package/src/lib/border.test.ts +83 -0
  64. package/src/lib/border.ts +170 -0
  65. package/src/lib/bunfs.test.ts +27 -0
  66. package/src/lib/bunfs.ts +18 -0
  67. package/src/lib/clipboard.test.ts +63 -0
  68. package/src/lib/clipboard.ts +41 -0
  69. package/src/lib/clock.ts +35 -0
  70. package/src/lib/data-paths.test.ts +133 -0
  71. package/src/lib/data-paths.ts +109 -0
  72. package/src/lib/debounce.ts +106 -0
  73. package/src/lib/detect-links.test.ts +98 -0
  74. package/src/lib/detect-links.ts +56 -0
  75. package/src/lib/env.test.ts +228 -0
  76. package/src/lib/env.ts +209 -0
  77. package/src/lib/extmarks-history.ts +51 -0
  78. package/src/lib/extmarks-multiwidth.test.ts +324 -0
  79. package/src/lib/extmarks.test.ts +3547 -0
  80. package/src/lib/extmarks.ts +861 -0
  81. package/src/lib/fonts/block.json +405 -0
  82. package/src/lib/fonts/grid.json +265 -0
  83. package/src/lib/fonts/huge.json +741 -0
  84. package/src/lib/fonts/pallet.json +314 -0
  85. package/src/lib/fonts/shade.json +591 -0
  86. package/src/lib/fonts/slick.json +321 -0
  87. package/src/lib/fonts/tiny.json +69 -0
  88. package/src/lib/hast-styled-text.ts +59 -0
  89. package/src/lib/index.ts +22 -0
  90. package/src/lib/keybinding.internal.test.ts +342 -0
  91. package/src/lib/keybinding.internal.ts +182 -0
  92. package/src/lib/objects-in-viewport.test.ts +789 -0
  93. package/src/lib/objects-in-viewport.ts +153 -0
  94. package/src/lib/output.capture.ts +58 -0
  95. package/src/lib/parse.keypress-kitty.protocol.test.ts +347 -0
  96. package/src/lib/parse.keypress-kitty.test.ts +712 -0
  97. package/src/lib/parse.keypress-kitty.ts +470 -0
  98. package/src/lib/parse.keypress.test.ts +2020 -0
  99. package/src/lib/parse.keypress.ts +480 -0
  100. package/src/lib/parse.mouse.test.ts +552 -0
  101. package/src/lib/parse.mouse.ts +232 -0
  102. package/src/lib/paste.ts +18 -0
  103. package/src/lib/queue.ts +65 -0
  104. package/src/lib/render-geometry.ts +36 -0
  105. package/src/lib/renderable.validations.test.ts +87 -0
  106. package/src/lib/renderable.validations.ts +83 -0
  107. package/src/lib/scroll-acceleration.ts +98 -0
  108. package/src/lib/selection.ts +261 -0
  109. package/src/lib/singleton.ts +34 -0
  110. package/src/lib/stdin-parser.test.ts +2439 -0
  111. package/src/lib/stdin-parser.ts +2007 -0
  112. package/src/lib/styled-text.ts +178 -0
  113. package/src/lib/terminal-capability-detection.test.ts +226 -0
  114. package/src/lib/terminal-capability-detection.ts +98 -0
  115. package/src/lib/terminal-palette.test.ts +954 -0
  116. package/src/lib/terminal-palette.ts +441 -0
  117. package/src/lib/tree-sitter/assets/README.md +119 -0
  118. package/src/lib/tree-sitter/assets/javascript/highlights.scm +205 -0
  119. package/src/lib/tree-sitter/assets/javascript/tree-sitter-javascript.wasm +0 -0
  120. package/src/lib/tree-sitter/assets/markdown/highlights.scm +150 -0
  121. package/src/lib/tree-sitter/assets/markdown/injections.scm +27 -0
  122. package/src/lib/tree-sitter/assets/markdown/tree-sitter-markdown.wasm +0 -0
  123. package/src/lib/tree-sitter/assets/markdown_inline/highlights.scm +115 -0
  124. package/src/lib/tree-sitter/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  125. package/src/lib/tree-sitter/assets/typescript/highlights.scm +604 -0
  126. package/src/lib/tree-sitter/assets/typescript/tree-sitter-typescript.wasm +0 -0
  127. package/src/lib/tree-sitter/assets/update.ts +360 -0
  128. package/src/lib/tree-sitter/assets/zig/highlights.scm +284 -0
  129. package/src/lib/tree-sitter/assets/zig/tree-sitter-zig.wasm +0 -0
  130. package/src/lib/tree-sitter/assets.d.ts +9 -0
  131. package/src/lib/tree-sitter/cache.test.ts +291 -0
  132. package/src/lib/tree-sitter/client.test.ts +1434 -0
  133. package/src/lib/tree-sitter/client.ts +847 -0
  134. package/src/lib/tree-sitter/default-parsers.ts +133 -0
  135. package/src/lib/tree-sitter/download-utils.ts +148 -0
  136. package/src/lib/tree-sitter/index.ts +75 -0
  137. package/src/lib/tree-sitter/parser.worker.ts +1098 -0
  138. package/src/lib/tree-sitter/parsers-config.ts +81 -0
  139. package/src/lib/tree-sitter/resolve-ft.test.ts +55 -0
  140. package/src/lib/tree-sitter/resolve-ft.ts +189 -0
  141. package/src/lib/tree-sitter/types.ts +132 -0
  142. package/src/lib/tree-sitter/update-assets.ts +10 -0
  143. package/src/lib/tree-sitter-styled-text.test.ts +1253 -0
  144. package/src/lib/tree-sitter-styled-text.ts +314 -0
  145. package/src/lib/validate-dir-name.ts +55 -0
  146. package/src/lib/yoga.options.test.ts +628 -0
  147. package/src/lib/yoga.options.ts +346 -0
  148. package/src/native-event-worker-repro.test.ts +48 -0
  149. package/src/native-event-worker-repro.worker.ts +9 -0
  150. package/src/native-handle.test.ts +221 -0
  151. package/src/platform/ffi.test.ts +516 -0
  152. package/src/platform/ffi.ts +653 -0
  153. package/src/platform/runtime.test.ts +52 -0
  154. package/src/platform/runtime.ts +121 -0
  155. package/src/platform/test.ts +45 -0
  156. package/src/platform/worker-handler-cleanup.fixture.ts +12 -0
  157. package/src/platform/worker-onmessage-startup.fixture.ts +10 -0
  158. package/src/platform/worker-startup.fixture.ts +9 -0
  159. package/src/platform/worker.node-test.ts +153 -0
  160. package/src/platform/worker.ts +425 -0
  161. package/src/plugins/core-slot.ts +579 -0
  162. package/src/plugins/registry.ts +402 -0
  163. package/src/plugins/types.ts +46 -0
  164. package/src/post/effects.ts +948 -0
  165. package/src/post/filters.ts +512 -0
  166. package/src/post/matrices.ts +288 -0
  167. package/src/renderables/ASCIIFont.ts +219 -0
  168. package/src/renderables/Box.test.ts +474 -0
  169. package/src/renderables/Box.ts +353 -0
  170. package/src/renderables/Code.test.ts +2388 -0
  171. package/src/renderables/Code.ts +555 -0
  172. package/src/renderables/Diff.regression.test.ts +381 -0
  173. package/src/renderables/Diff.test.ts +3212 -0
  174. package/src/renderables/Diff.ts +1278 -0
  175. package/src/renderables/EditBufferRenderable.test.ts +288 -0
  176. package/src/renderables/EditBufferRenderable.ts +1152 -0
  177. package/src/renderables/FrameBuffer.ts +47 -0
  178. package/src/renderables/Input.test.ts +1310 -0
  179. package/src/renderables/Input.ts +273 -0
  180. package/src/renderables/LineNumberRenderable.ts +725 -0
  181. package/src/renderables/Markdown.ts +2144 -0
  182. package/src/renderables/ScrollBar.ts +423 -0
  183. package/src/renderables/ScrollBox.ts +903 -0
  184. package/src/renderables/Select.test.ts +1134 -0
  185. package/src/renderables/Select.ts +535 -0
  186. package/src/renderables/Slider.test.ts +456 -0
  187. package/src/renderables/Slider.ts +342 -0
  188. package/src/renderables/TabSelect.test.ts +238 -0
  189. package/src/renderables/TabSelect.ts +447 -0
  190. package/src/renderables/Text.selection-buffer.test.ts +118 -0
  191. package/src/renderables/Text.test.ts +2662 -0
  192. package/src/renderables/Text.ts +147 -0
  193. package/src/renderables/TextBufferRenderable.ts +504 -0
  194. package/src/renderables/TextNode.test.ts +1137 -0
  195. package/src/renderables/TextNode.ts +379 -0
  196. package/src/renderables/TextTable.test.ts +1411 -0
  197. package/src/renderables/TextTable.ts +1434 -0
  198. package/src/renderables/Textarea.ts +425 -0
  199. package/src/renderables/TimeToFirstDraw.ts +89 -0
  200. package/src/renderables/__snapshots__/Code.test.ts.snap +13 -0
  201. package/src/renderables/__snapshots__/Diff.test.ts.snap +785 -0
  202. package/src/renderables/__snapshots__/Text.test.ts.snap +421 -0
  203. package/src/renderables/__snapshots__/TextTable.test.ts.snap +215 -0
  204. package/src/renderables/__tests__/Code.test.ts +55 -0
  205. package/src/renderables/__tests__/LineNumberRenderable.scrollbox-simple.test.ts +144 -0
  206. package/src/renderables/__tests__/LineNumberRenderable.scrollbox.test.ts +827 -0
  207. package/src/renderables/__tests__/LineNumberRenderable.test.ts +1906 -0
  208. package/src/renderables/__tests__/LineNumberRenderable.wrapping.test.ts +85 -0
  209. package/src/renderables/__tests__/Markdown.code-colors.test.ts +288 -0
  210. package/src/renderables/__tests__/Markdown.test.ts +4175 -0
  211. package/src/renderables/__tests__/MultiRenderable.selection.test.ts +87 -0
  212. package/src/renderables/__tests__/Textarea.buffer.test.ts +683 -0
  213. package/src/renderables/__tests__/Textarea.destroyed-events.test.ts +675 -0
  214. package/src/renderables/__tests__/Textarea.editing.test.ts +2120 -0
  215. package/src/renderables/__tests__/Textarea.error-handling.test.ts +35 -0
  216. package/src/renderables/__tests__/Textarea.events.test.ts +738 -0
  217. package/src/renderables/__tests__/Textarea.highlights.test.ts +590 -0
  218. package/src/renderables/__tests__/Textarea.keybinding.test.ts +3275 -0
  219. package/src/renderables/__tests__/Textarea.paste.test.ts +357 -0
  220. package/src/renderables/__tests__/Textarea.rendering.test.ts +1927 -0
  221. package/src/renderables/__tests__/Textarea.scroll.test.ts +733 -0
  222. package/src/renderables/__tests__/Textarea.selection.test.ts +1589 -0
  223. package/src/renderables/__tests__/Textarea.stress.test.ts +670 -0
  224. package/src/renderables/__tests__/Textarea.undo-redo.test.ts +383 -0
  225. package/src/renderables/__tests__/Textarea.visual-lines.test.ts +310 -0
  226. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.code.test.ts.snap +221 -0
  227. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox-simple.test.ts.snap +89 -0
  228. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox.test.ts.snap +457 -0
  229. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.test.ts.snap +158 -0
  230. package/src/renderables/__tests__/__snapshots__/Textarea.rendering.test.ts.snap +387 -0
  231. package/src/renderables/__tests__/markdown-parser.test.ts +241 -0
  232. package/src/renderables/__tests__/renderable-test-utils.ts +60 -0
  233. package/src/renderables/composition/README.md +8 -0
  234. package/src/renderables/composition/VRenderable.ts +32 -0
  235. package/src/renderables/composition/constructs.ts +127 -0
  236. package/src/renderables/composition/vnode.ts +277 -0
  237. package/src/renderables/index.ts +23 -0
  238. package/src/renderables/markdown-parser.ts +79 -0
  239. package/src/renderer-theme-mode.ts +199 -0
  240. package/src/renderer.ts +4975 -0
  241. package/src/runtime-plugin-support-configure.ts +63 -0
  242. package/src/runtime-plugin-support.ts +13 -0
  243. package/src/runtime-plugin.ts +626 -0
  244. package/src/specs/terminal-startup.md +64 -0
  245. package/src/syntax-style.test.ts +841 -0
  246. package/src/syntax-style.ts +274 -0
  247. package/src/testing/README.md +219 -0
  248. package/src/testing/bun-test-node.ts +880 -0
  249. package/src/testing/capture-spans.test.ts +216 -0
  250. package/src/testing/integration.test.ts +276 -0
  251. package/src/testing/manual-clock.ts +117 -0
  252. package/src/testing/mock-keys.test.ts +1378 -0
  253. package/src/testing/mock-keys.ts +457 -0
  254. package/src/testing/mock-mouse.test.ts +218 -0
  255. package/src/testing/mock-mouse.ts +247 -0
  256. package/src/testing/mock-tree-sitter-client.ts +81 -0
  257. package/src/testing/spy.ts +13 -0
  258. package/src/testing/terminal-capabilities.ts +47 -0
  259. package/src/testing/test-recorder.test.ts +410 -0
  260. package/src/testing/test-recorder.ts +133 -0
  261. package/src/testing/test-renderer.ts +375 -0
  262. package/src/testing/test-renderer.wait.test.ts +278 -0
  263. package/src/testing/test-streams.ts +31 -0
  264. package/src/testing.ts +9 -0
  265. package/src/tests/__snapshots__/absolute-positioning.snapshot.test.ts.snap +481 -0
  266. package/src/tests/__snapshots__/renderable.snapshot.test.ts.snap +19 -0
  267. package/src/tests/__snapshots__/scrollbox.test.ts.snap +29 -0
  268. package/src/tests/absolute-positioning.snapshot.test.ts +638 -0
  269. package/src/tests/allocator-stats.test.ts +53 -0
  270. package/src/tests/audio.test.ts +303 -0
  271. package/src/tests/destroy-during-render.test.ts +200 -0
  272. package/src/tests/destroy-on-exit.fixture.ts +36 -0
  273. package/src/tests/destroy-on-exit.test.ts +62 -0
  274. package/src/tests/ffi-borrowed-pointer-callsites.test.ts +153 -0
  275. package/src/tests/hover-cursor.test.ts +98 -0
  276. package/src/tests/native-backed-measurement-lifecycle.test.ts +133 -0
  277. package/src/tests/native-backed-measurement-parity.test.ts +322 -0
  278. package/src/tests/native-span-feed-async.test.ts +173 -0
  279. package/src/tests/native-span-feed-close.test.ts +120 -0
  280. package/src/tests/native-span-feed-coverage.test.ts +227 -0
  281. package/src/tests/native-span-feed-edge-cases.test.ts +384 -0
  282. package/src/tests/native-span-feed-use-after-free.test.ts +45 -0
  283. package/src/tests/opacity.test.ts +123 -0
  284. package/src/tests/renderable.snapshot.test.ts +524 -0
  285. package/src/tests/renderable.test.ts +1851 -0
  286. package/src/tests/renderer.clock.test.ts +270 -0
  287. package/src/tests/renderer.console-startup.test.ts +2151 -0
  288. package/src/tests/renderer.control.test.ts +458 -0
  289. package/src/tests/renderer.core-slot-binding.test.ts +962 -0
  290. package/src/tests/renderer.cursor.test.ts +26 -0
  291. package/src/tests/renderer.custom-stdout.test.ts +1112 -0
  292. package/src/tests/renderer.destroy-during-render.test.ts +147 -0
  293. package/src/tests/renderer.focus-restore.test.ts +257 -0
  294. package/src/tests/renderer.focus.test.ts +329 -0
  295. package/src/tests/renderer.idle.test.ts +219 -0
  296. package/src/tests/renderer.input.test.ts +2615 -0
  297. package/src/tests/renderer.kitty-flags.test.ts +195 -0
  298. package/src/tests/renderer.lifecycle.test.ts +34 -0
  299. package/src/tests/renderer.mouse.test.ts +1315 -0
  300. package/src/tests/renderer.notifications.test.ts +27 -0
  301. package/src/tests/renderer.palette.test.ts +1199 -0
  302. package/src/tests/renderer.remote.test.ts +247 -0
  303. package/src/tests/renderer.render-stats.test.ts +146 -0
  304. package/src/tests/renderer.scrollback-surface.test.ts +474 -0
  305. package/src/tests/renderer.selection.test.ts +138 -0
  306. package/src/tests/renderer.slot-registry.test.ts +684 -0
  307. package/src/tests/renderer.tracker.test.ts +202 -0
  308. package/src/tests/renderer.useMouse.test.ts +83 -0
  309. package/src/tests/runtime-plugin-node-modules-cycle.fixture.ts +76 -0
  310. package/src/tests/runtime-plugin-node-modules-import-like-string.fixture.ts +48 -0
  311. package/src/tests/runtime-plugin-node-modules-mjs.fixture.ts +43 -0
  312. package/src/tests/runtime-plugin-node-modules-no-bare-rewrite.fixture.ts +67 -0
  313. package/src/tests/runtime-plugin-node-modules-package-type-cache.fixture.ts +72 -0
  314. package/src/tests/runtime-plugin-node-modules-runtime-specifier.fixture.ts +44 -0
  315. package/src/tests/runtime-plugin-node-modules-scoped-package-bare-rewrite.fixture.ts +85 -0
  316. package/src/tests/runtime-plugin-path-alias.fixture.ts +43 -0
  317. package/src/tests/runtime-plugin-resolve-roots.fixture.ts +65 -0
  318. package/src/tests/runtime-plugin-support-configure.fixture.ts +31 -0
  319. package/src/tests/runtime-plugin-support-late-addition.fixture.ts +17 -0
  320. package/src/tests/runtime-plugin-support.fixture.ts +11 -0
  321. package/src/tests/runtime-plugin-support.test.ts +54 -0
  322. package/src/tests/runtime-plugin-windows-file-url.fixture.ts +30 -0
  323. package/src/tests/runtime-plugin.fixture.ts +40 -0
  324. package/src/tests/runtime-plugin.test.ts +369 -0
  325. package/src/tests/scrollbox-culling-bug.test.ts +114 -0
  326. package/src/tests/scrollbox-hitgrid-resize.test.ts +136 -0
  327. package/src/tests/scrollbox-hitgrid.test.ts +909 -0
  328. package/src/tests/scrollbox.test.ts +1895 -0
  329. package/src/tests/wrap-resize-perf.test.ts +276 -0
  330. package/src/tests/yoga-api-coverage.test.ts +409 -0
  331. package/src/tests/yoga-callback-stress.test.ts +122 -0
  332. package/src/tests/yoga-ffi.test.ts +117 -0
  333. package/src/tests/yoga-setters.test.ts +921 -0
  334. package/src/tests/yoga-upstream/YGAlignBaselineTest.test.ts +124 -0
  335. package/src/tests/yoga-upstream/YGComputedBorderTest.test.ts +27 -0
  336. package/src/tests/yoga-upstream/YGComputedMarginTest.test.ts +27 -0
  337. package/src/tests/yoga-upstream/YGComputedPaddingTest.test.ts +27 -0
  338. package/src/tests/yoga-upstream/YGDirtiedTest.test.ts +157 -0
  339. package/src/tests/yoga-upstream/YGErrataTest.test.ts +40 -0
  340. package/src/tests/yoga-upstream/YGFlexBasisAuto.test.ts +23 -0
  341. package/src/tests/yoga-upstream/YGHasNewLayout.test.ts +81 -0
  342. package/src/tests/yoga-upstream/YGMeasureCacheTest.test.ts +31 -0
  343. package/src/tests/yoga-upstream/YGMeasureTest.test.ts +70 -0
  344. package/src/tests/yoga-upstream/generated/YGAbsolutePositionTest.test.ts +1864 -0
  345. package/src/tests/yoga-upstream/generated/YGAlignContentTest.test.ts +5829 -0
  346. package/src/tests/yoga-upstream/generated/YGAlignItemsTest.test.ts +2444 -0
  347. package/src/tests/yoga-upstream/generated/YGAlignSelfTest.test.ts +293 -0
  348. package/src/tests/yoga-upstream/generated/YGAndroidNewsFeed.test.ts +315 -0
  349. package/src/tests/yoga-upstream/generated/YGAspectRatioTest.test.ts +231 -0
  350. package/src/tests/yoga-upstream/generated/YGAutoTest.test.ts +347 -0
  351. package/src/tests/yoga-upstream/generated/YGBorderTest.test.ts +256 -0
  352. package/src/tests/yoga-upstream/generated/YGBoxSizingTest.test.ts +2747 -0
  353. package/src/tests/yoga-upstream/generated/YGDimensionTest.test.ts +129 -0
  354. package/src/tests/yoga-upstream/generated/YGDisplayContentsTest.test.ts +109 -0
  355. package/src/tests/yoga-upstream/generated/YGDisplayTest.test.ts +1097 -0
  356. package/src/tests/yoga-upstream/generated/YGFlexDirectionTest.test.ts +4562 -0
  357. package/src/tests/yoga-upstream/generated/YGFlexTest.test.ts +677 -0
  358. package/src/tests/yoga-upstream/generated/YGFlexWrapTest.test.ts +2071 -0
  359. package/src/tests/yoga-upstream/generated/YGGapTest.test.ts +3303 -0
  360. package/src/tests/yoga-upstream/generated/YGIntrinsicSizeTest.test.ts +582 -0
  361. package/src/tests/yoga-upstream/generated/YGJustifyContentTest.test.ts +2150 -0
  362. package/src/tests/yoga-upstream/generated/YGMarginTest.test.ts +1963 -0
  363. package/src/tests/yoga-upstream/generated/YGMinMaxDimensionTest.test.ts +1446 -0
  364. package/src/tests/yoga-upstream/generated/YGPaddingTest.test.ts +354 -0
  365. package/src/tests/yoga-upstream/generated/YGPercentageTest.test.ts +1760 -0
  366. package/src/tests/yoga-upstream/generated/YGRoundingTest.test.ts +1161 -0
  367. package/src/tests/yoga-upstream/generated/YGSizeOverflowTest.test.ts +207 -0
  368. package/src/tests/yoga-upstream/generated/YGStaticPositionTest.test.ts +6338 -0
  369. package/src/tests/yoga-upstream/tools/MeasureCounter.ts +54 -0
  370. package/src/tests/yoga-upstream/tools/utils.ts +81 -0
  371. package/src/text-buffer-view.test.ts +722 -0
  372. package/src/text-buffer-view.ts +193 -0
  373. package/src/text-buffer.test.ts +512 -0
  374. package/src/text-buffer.ts +250 -0
  375. package/src/types.ts +199 -0
  376. package/src/utils.ts +88 -0
  377. package/src/yoga.ts +1146 -0
  378. package/src/zig/ansi.zig +502 -0
  379. package/src/zig/audio.zig +1206 -0
  380. package/src/zig/bench/README.md +50 -0
  381. package/src/zig/bench/buffer-color-blending_bench.zig +350 -0
  382. package/src/zig/bench/buffer-draw-box_bench.zig +786 -0
  383. package/src/zig/bench/buffer-draw-text-buffer_bench.zig +894 -0
  384. package/src/zig/bench/edit-buffer_bench.zig +476 -0
  385. package/src/zig/bench/editor-view_bench.zig +169 -0
  386. package/src/zig/bench/native-span-feed_bench.zig +107 -0
  387. package/src/zig/bench/rope-markers_bench.zig +713 -0
  388. package/src/zig/bench/rope_bench.zig +514 -0
  389. package/src/zig/bench/styled-text_bench.zig +476 -0
  390. package/src/zig/bench/text-buffer-coords_bench.zig +362 -0
  391. package/src/zig/bench/text-buffer-view_bench.zig +459 -0
  392. package/src/zig/bench/text-chunk-graphemes_bench.zig +272 -0
  393. package/src/zig/bench/utf8_bench.zig +799 -0
  394. package/src/zig/bench-utils.zig +431 -0
  395. package/src/zig/bench.zig +223 -0
  396. package/src/zig/buffer-methods.zig +215 -0
  397. package/src/zig/buffer.zig +2515 -0
  398. package/src/zig/build.zig +700 -0
  399. package/src/zig/build.zig.zon +19 -0
  400. package/src/zig/edit-buffer.zig +900 -0
  401. package/src/zig/editor-view.zig +812 -0
  402. package/src/zig/event-bus.zig +28 -0
  403. package/src/zig/event-emitter.zig +65 -0
  404. package/src/zig/file-logger.zig +92 -0
  405. package/src/zig/grapheme.zig +838 -0
  406. package/src/zig/handles.zig +267 -0
  407. package/src/zig/lib.zig +2813 -0
  408. package/src/zig/link.zig +349 -0
  409. package/src/zig/logger.zig +43 -0
  410. package/src/zig/mem-registry.zig +126 -0
  411. package/src/zig/miniaudio_shim.c +21 -0
  412. package/src/zig/native-renderable.zig +112 -0
  413. package/src/zig/native-span-feed-bench-lib.zig +7 -0
  414. package/src/zig/native-span-feed.zig +747 -0
  415. package/src/zig/renderer-output.zig +677 -0
  416. package/src/zig/renderer.zig +2106 -0
  417. package/src/zig/rope.zig +1220 -0
  418. package/src/zig/split-scrollback.zig +88 -0
  419. package/src/zig/syntax-style.zig +174 -0
  420. package/src/zig/terminal.zig +1652 -0
  421. package/src/zig/test.zig +82 -0
  422. package/src/zig/tests/README.md +18 -0
  423. package/src/zig/tests/ansi_test.zig +18 -0
  424. package/src/zig/tests/audio_test.zig +439 -0
  425. package/src/zig/tests/buffer-methods_test.zig +1111 -0
  426. package/src/zig/tests/buffer_test.zig +2926 -0
  427. package/src/zig/tests/edit-buffer-history_test.zig +299 -0
  428. package/src/zig/tests/edit-buffer_test.zig +1688 -0
  429. package/src/zig/tests/editor-view_test.zig +3454 -0
  430. package/src/zig/tests/event-emitter_test.zig +249 -0
  431. package/src/zig/tests/grapheme_test.zig +1329 -0
  432. package/src/zig/tests/handles_test.zig +123 -0
  433. package/src/zig/tests/link_test.zig +220 -0
  434. package/src/zig/tests/mem-registry_test.zig +473 -0
  435. package/src/zig/tests/memory_leak_regression_test.zig +234 -0
  436. package/src/zig/tests/native-renderable_test.zig +16 -0
  437. package/src/zig/tests/native-span-feed_test.zig +1266 -0
  438. package/src/zig/tests/renderer_test.zig +2604 -0
  439. package/src/zig/tests/rope-nested_test.zig +712 -0
  440. package/src/zig/tests/rope_fuzz_test.zig +238 -0
  441. package/src/zig/tests/rope_test.zig +2362 -0
  442. package/src/zig/tests/segment-merge.test.zig +148 -0
  443. package/src/zig/tests/split-scrollback_test.zig +70 -0
  444. package/src/zig/tests/syntax-style_test.zig +558 -0
  445. package/src/zig/tests/terminal_test.zig +1489 -0
  446. package/src/zig/tests/test-renderer.zig +126 -0
  447. package/src/zig/tests/text-buffer-drawing_test.zig +3291 -0
  448. package/src/zig/tests/text-buffer-highlights_test.zig +706 -0
  449. package/src/zig/tests/text-buffer-iterators_test.zig +776 -0
  450. package/src/zig/tests/text-buffer-segment_test.zig +320 -0
  451. package/src/zig/tests/text-buffer-selection_test.zig +1056 -0
  452. package/src/zig/tests/text-buffer-selection_viewport_test.zig +358 -0
  453. package/src/zig/tests/text-buffer-view_test.zig +3672 -0
  454. package/src/zig/tests/text-buffer_test.zig +2191 -0
  455. package/src/zig/tests/unicode-width-map.zon +3909 -0
  456. package/src/zig/tests/utf8_no_zwj_test.zig +260 -0
  457. package/src/zig/tests/utf8_test.zig +4060 -0
  458. package/src/zig/tests/utf8_wcwidth_cursor_test.zig +267 -0
  459. package/src/zig/tests/utf8_wcwidth_test.zig +357 -0
  460. package/src/zig/tests/word-wrap-editing_test.zig +498 -0
  461. package/src/zig/tests/wrap-cache-perf_test.zig +113 -0
  462. package/src/zig/tests/yoga_test.zig +65 -0
  463. package/src/zig/text-buffer-iterators.zig +496 -0
  464. package/src/zig/text-buffer-segment.zig +403 -0
  465. package/src/zig/text-buffer-view.zig +1428 -0
  466. package/src/zig/text-buffer.zig +1272 -0
  467. package/src/zig/utf8.zig +1954 -0
  468. package/src/zig/utils.zig +12 -0
  469. package/src/zig/uucode-stub.zig +76 -0
  470. package/src/zig/vendor/miniaudio/miniaudio.h +93468 -0
  471. package/src/zig/yoga.zig +658 -0
  472. package/src/zig-structs.ts +381 -0
  473. package/src/zig.ts +5260 -0
  474. package/tsconfig.build.json +17 -0
  475. package/tsconfig.json +27 -0
  476. package/tsconfig.node-test.json +138 -0
@@ -0,0 +1,2007 @@
1
+ // Byte-level stdin parser that turns raw terminal input into typed StdinEvents.
2
+ //
3
+ // This replaces a two-phase token -> decode pipeline with a single state machine
4
+ // that produces fully typed events (key, mouse, paste, response) directly from
5
+ // bytes. The parser owns all byte framing and protocol recognition. It does NOT
6
+ // own event dispatch — that belongs to KeyHandler and the renderer.
7
+
8
+ import { Buffer } from "node:buffer"
9
+ import { SystemClock, type Clock, type TimerHandle } from "./clock.js"
10
+ import { parseKeypress, type ParsedKey } from "./parse.keypress.js"
11
+ import { MouseParser, type RawMouseEvent } from "./parse.mouse.js"
12
+ import type { PasteMetadata } from "./paste.js"
13
+
14
+ export { SystemClock, type Clock, type TimerHandle } from "./clock.js"
15
+
16
+ export type StdinResponseProtocol = "csi" | "cpr" | "osc" | "dcs" | "apc" | "unknown"
17
+
18
+ // The four event types the parser produces. Everything stdin sends becomes
19
+ // exactly one of these.
20
+ export type StdinEvent =
21
+ | {
22
+ type: "key"
23
+ raw: string
24
+ key: ParsedKey
25
+ }
26
+ | {
27
+ type: "mouse"
28
+ raw: string
29
+ encoding: "sgr" | "x10"
30
+ event: RawMouseEvent
31
+ }
32
+ | {
33
+ type: "paste"
34
+ bytes: Uint8Array
35
+ metadata?: PasteMetadata
36
+ }
37
+ | {
38
+ type: "response"
39
+ protocol: StdinResponseProtocol
40
+ sequence: string
41
+ }
42
+
43
+ export interface StdinParserProtocolContext {
44
+ kittyKeyboardEnabled: boolean
45
+ privateCapabilityRepliesActive: boolean
46
+ pixelResolutionQueryActive: boolean
47
+ explicitWidthCprActive: boolean
48
+ startupCursorCprActive: boolean
49
+ }
50
+
51
+ export interface StdinParserOptions {
52
+ timeoutMs?: number
53
+ maxPendingBytes?: number
54
+ armTimeouts?: boolean
55
+ onTimeoutFlush?: () => void
56
+ useKittyKeyboard?: boolean
57
+ protocolContext?: Partial<StdinParserProtocolContext>
58
+ clock?: Clock
59
+ }
60
+
61
+ // State machine tags for the byte scanner. Each tag represents which protocol
62
+ // framing mode the parser is currently inside. The sawEsc flag in osc/dcs/apc
63
+ // tracks whether the previous byte was ESC, since the two-byte ST terminator
64
+ // (ESC \) can split across push() calls.
65
+ type ParserState =
66
+ | { tag: "ground" }
67
+ | { tag: "utf8"; expected: number; seen: number }
68
+ | { tag: "esc" }
69
+ | { tag: "ss3" }
70
+ | { tag: "csi" }
71
+ | { tag: "csi_sgr_mouse"; part: number; hasDigit: boolean }
72
+ | { tag: "csi_sgr_mouse_deferred"; part: number; hasDigit: boolean }
73
+ | { tag: "csi_parametric"; semicolons: number; segments: number; hasDigit: boolean; firstParamValue: number | null }
74
+ | {
75
+ tag: "csi_parametric_deferred"
76
+ semicolons: number
77
+ segments: number
78
+ hasDigit: boolean
79
+ firstParamValue: number | null
80
+ }
81
+ | {
82
+ // Startup cursor CPR cancellation can happen before the parser has enough
83
+ // bytes to distinguish a stale reply from ordinary CSI input. This state
84
+ // keeps consuming that one pending reply until it is either discarded as
85
+ // CPR noise or handed back to normal CSI parsing.
86
+ tag: "csi_parametric_ignored"
87
+ semicolons: number
88
+ segments: number
89
+ hasDigit: boolean
90
+ firstParamValue: number | null
91
+ }
92
+ | { tag: "csi_private_reply"; semicolons: number; hasDigit: boolean; sawDollar: boolean }
93
+ | { tag: "csi_private_reply_deferred"; semicolons: number; hasDigit: boolean; sawDollar: boolean }
94
+ | { tag: "osc"; sawEsc: boolean }
95
+ | { tag: "dcs"; sawEsc: boolean }
96
+ | { tag: "apc"; sawEsc: boolean }
97
+ | { tag: "esc_recovery" }
98
+ | { tag: "esc_less_mouse" }
99
+ | { tag: "esc_less_x10_mouse" }
100
+
101
+ // Collects paste body incrementally, bypassing the main ByteQueue so large
102
+ // pastes don't grow the parser buffer. Keeps only a small tail for end-marker
103
+ // detection across chunk boundaries.
104
+ interface PasteCollector {
105
+ tail: Uint8Array
106
+ parts: Uint8Array[]
107
+ totalLength: number
108
+ }
109
+
110
+ // 20ms is to distinguish a lone ESC keypress from the start of an
111
+ // escape sequence. Gemini/Claude uses 50ms, Codex uses 20ms, trying
112
+ // this as a balanced default for now.
113
+ const DEFAULT_TIMEOUT_MS = 20
114
+ const DEFAULT_MAX_PENDING_BYTES = 64 * 1024
115
+ const INITIAL_PENDING_CAPACITY = 256
116
+ const ESC = 0x1b
117
+ const BEL = 0x07
118
+ const BRACKETED_PASTE_START = Buffer.from("\x1b[200~")
119
+ const BRACKETED_PASTE_END = Buffer.from("\x1b[201~")
120
+ const EMPTY_BYTES = new Uint8Array(0)
121
+ const KEY_DECODER = new TextDecoder()
122
+ const DEFAULT_PROTOCOL_CONTEXT: StdinParserProtocolContext = {
123
+ kittyKeyboardEnabled: false,
124
+ privateCapabilityRepliesActive: false,
125
+ pixelResolutionQueryActive: false,
126
+ explicitWidthCprActive: false,
127
+ startupCursorCprActive: false,
128
+ }
129
+ // rxvt uses $-terminated CSI sequences for shifted function keys (e.g. ESC[2$).
130
+ // Standard CSI treats $ as an intermediate byte, not a final, so we match these
131
+ // explicitly to avoid waiting for a "real" final byte that never arrives.
132
+ const RXVT_DOLLAR_CSI_RE = /^\x1b\[\d+\$$/
133
+
134
+ const SYSTEM_CLOCK = new SystemClock()
135
+
136
+ // Byte buffer for pending input. Uses start/end offsets so consume() just
137
+ // advances the start pointer without copying. Compacts (via copyWithin) only
138
+ // when the consumed prefix exceeds half the buffer, keeping amortized cost low.
139
+ class ByteQueue {
140
+ private buf: Uint8Array
141
+ private start = 0
142
+ private end = 0
143
+
144
+ constructor(capacity = INITIAL_PENDING_CAPACITY) {
145
+ this.buf = new Uint8Array(capacity)
146
+ }
147
+
148
+ get length(): number {
149
+ return this.end - this.start
150
+ }
151
+
152
+ get capacity(): number {
153
+ return this.buf.length
154
+ }
155
+
156
+ view(): Uint8Array {
157
+ return this.buf.subarray(this.start, this.end)
158
+ }
159
+
160
+ // Returns a view of the contents and resets the queue. The view shares
161
+ // the underlying buffer, so it becomes invalid on the next append().
162
+ take(): Uint8Array {
163
+ const chunk = this.view()
164
+ this.start = 0
165
+ this.end = 0
166
+ return chunk
167
+ }
168
+
169
+ append(chunk: Uint8Array): void {
170
+ if (chunk.length === 0) {
171
+ return
172
+ }
173
+
174
+ this.ensureCapacity(this.length + chunk.length)
175
+ this.buf.set(chunk, this.end)
176
+ this.end += chunk.length
177
+ }
178
+
179
+ // Drops the first `count` bytes. Compacts when the consumed prefix
180
+ // exceeds half the buffer to reclaim wasted space at the front.
181
+ consume(count: number): void {
182
+ if (count <= 0) {
183
+ return
184
+ }
185
+
186
+ if (count >= this.length) {
187
+ this.start = 0
188
+ this.end = 0
189
+ return
190
+ }
191
+
192
+ this.start += count
193
+ if (this.start >= this.buf.length / 2) {
194
+ this.buf.copyWithin(0, this.start, this.end)
195
+ this.end -= this.start
196
+ this.start = 0
197
+ }
198
+ }
199
+
200
+ clear(): void {
201
+ this.start = 0
202
+ this.end = 0
203
+ }
204
+
205
+ reset(capacity = INITIAL_PENDING_CAPACITY): void {
206
+ this.buf = new Uint8Array(capacity)
207
+ this.start = 0
208
+ this.end = 0
209
+ }
210
+
211
+ // Tries reclaiming space by compacting data to the front first.
212
+ // Doubles the allocation if that still isn't enough.
213
+ private ensureCapacity(requiredLength: number): void {
214
+ const currentLength = this.length
215
+ if (requiredLength <= this.buf.length) {
216
+ const availableAtEnd = this.buf.length - this.end
217
+ if (availableAtEnd >= requiredLength - currentLength) {
218
+ return
219
+ }
220
+
221
+ this.buf.copyWithin(0, this.start, this.end)
222
+ this.end = currentLength
223
+ this.start = 0
224
+ if (requiredLength <= this.buf.length) {
225
+ return
226
+ }
227
+ }
228
+
229
+ let nextCapacity = this.buf.length
230
+ while (nextCapacity < requiredLength) {
231
+ nextCapacity *= 2
232
+ }
233
+
234
+ const next = new Uint8Array(nextCapacity)
235
+ next.set(this.view(), 0)
236
+ this.buf = next
237
+ this.start = 0
238
+ this.end = currentLength
239
+ }
240
+ }
241
+
242
+ function normalizePositiveOption(value: number | undefined, fallback: number): number {
243
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
244
+ return fallback
245
+ }
246
+
247
+ return Math.floor(value)
248
+ }
249
+
250
+ // Returns the expected byte count for a UTF-8 sequence given its lead byte,
251
+ // or 0 for bytes that aren't valid UTF-8 leads. Returning 0 tells the parser
252
+ // this is a legacy high-byte character (0x80–0xBF, 0xC0–0xC1, 0xF5+) that
253
+ // goes through the parseKeypress() meta-key path instead.
254
+ function utf8SequenceLength(first: number): number {
255
+ if (first < 0x80) return 1
256
+ if (first >= 0xc2 && first <= 0xdf) return 2
257
+ if (first >= 0xe0 && first <= 0xef) return 3
258
+ if (first >= 0xf0 && first <= 0xf4) return 4
259
+ return 0
260
+ }
261
+
262
+ function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {
263
+ if (left.length !== right.length) {
264
+ return false
265
+ }
266
+
267
+ for (let index = 0; index < left.length; index += 1) {
268
+ if (left[index] !== right[index]) {
269
+ return false
270
+ }
271
+ }
272
+
273
+ return true
274
+ }
275
+
276
+ // Checks whether a byte sequence is a complete SGR mouse report:
277
+ // ESC [ < Ps ; Ps ; Ps M/m (three semicolon-separated digit groups).
278
+ function isMouseSgrSequence(sequence: Uint8Array): boolean {
279
+ if (sequence.length < 7) {
280
+ return false
281
+ }
282
+
283
+ if (sequence[0] !== ESC || sequence[1] !== 0x5b || sequence[2] !== 0x3c) {
284
+ return false
285
+ }
286
+
287
+ const final = sequence[sequence.length - 1]
288
+ if (final !== 0x4d && final !== 0x6d) {
289
+ return false
290
+ }
291
+
292
+ let part = 0
293
+ let hasDigit = false
294
+ for (let index = 3; index < sequence.length - 1; index += 1) {
295
+ const byte = sequence[index]!
296
+ if (byte >= 0x30 && byte <= 0x39) {
297
+ hasDigit = true
298
+ continue
299
+ }
300
+
301
+ if (byte === 0x3b && hasDigit && part < 2) {
302
+ part += 1
303
+ hasDigit = false
304
+ continue
305
+ }
306
+
307
+ return false
308
+ }
309
+
310
+ return part === 2 && hasDigit
311
+ }
312
+
313
+ function isAsciiDigit(byte: number): boolean {
314
+ return byte >= 0x30 && byte <= 0x39
315
+ }
316
+
317
+ interface ParametricCsiLike {
318
+ semicolons: number
319
+ segments: number
320
+ hasDigit: boolean
321
+ firstParamValue: number | null
322
+ }
323
+
324
+ interface PrivateReplyCsiLike {
325
+ semicolons: number
326
+ hasDigit: boolean
327
+ sawDollar: boolean
328
+ }
329
+
330
+ function parsePositiveDecimalPrefix(sequence: Uint8Array, start: number, endExclusive: number): number | null {
331
+ if (start >= endExclusive) return null
332
+
333
+ let value = 0
334
+ let sawDigit = false
335
+ for (let index = start; index < endExclusive; index += 1) {
336
+ const byte = sequence[index]!
337
+ if (!isAsciiDigit(byte)) return null
338
+ sawDigit = true
339
+ value = value * 10 + (byte - 0x30)
340
+ }
341
+
342
+ return sawDigit ? value : null
343
+ }
344
+
345
+ // Returns the leading kitty codepoint from field 1, like `97` in `97:65`.
346
+ // The CSI scanner uses this at `;` boundaries to recognize alternate-key
347
+ // forms (`codepoint[:shifted[:base]]`). That keeps split kitty sequences
348
+ // pending, instead of flushing them as unknown on timeout.
349
+ function parseKittyFirstFieldCodepoint(sequence: Uint8Array, start: number, endExclusive: number): number | null {
350
+ if (start >= endExclusive) return null
351
+
352
+ let firstColon = -1
353
+ for (let index = start; index < endExclusive; index += 1) {
354
+ if (sequence[index] === 0x3a) {
355
+ firstColon = index
356
+ break
357
+ }
358
+ }
359
+
360
+ if (firstColon === -1) return null
361
+
362
+ const codepoint = parsePositiveDecimalPrefix(sequence, start, firstColon)
363
+ if (codepoint === null) return null
364
+
365
+ // Remaining bytes in field 1 must stay kitty-compatible: digits or colons.
366
+ for (let index = firstColon + 1; index < endExclusive; index += 1) {
367
+ const byte = sequence[index]!
368
+ if (byte !== 0x3a && !isAsciiDigit(byte)) return null
369
+ }
370
+
371
+ return codepoint
372
+ }
373
+
374
+ function canStillBeKittyU(state: ParametricCsiLike): boolean {
375
+ return state.semicolons >= 1
376
+ }
377
+
378
+ function canStillBeKittySpecial(state: ParametricCsiLike): boolean {
379
+ return state.semicolons === 1 && state.segments > 1
380
+ }
381
+
382
+ function canStillBeExplicitWidthCpr(state: ParametricCsiLike): boolean {
383
+ return state.firstParamValue === 1 && state.semicolons === 1
384
+ }
385
+
386
+ function canStillBeStartupCursorCpr(state: ParametricCsiLike): boolean {
387
+ return state.semicolons === 1
388
+ }
389
+
390
+ function canStillBeStartupCursorCprPrefix(state: ParametricCsiLike): boolean {
391
+ return state.segments === 1 && state.semicolons <= 1
392
+ }
393
+
394
+ function canStillBePixelResolution(state: ParametricCsiLike): boolean {
395
+ return state.firstParamValue === 4 && state.semicolons === 2
396
+ }
397
+
398
+ function canDeferParametricCsi(state: ParametricCsiLike, context: StdinParserProtocolContext): boolean {
399
+ return (
400
+ (context.kittyKeyboardEnabled && (canStillBeKittyU(state) || canStillBeKittySpecial(state))) ||
401
+ (context.explicitWidthCprActive && canStillBeExplicitWidthCpr(state)) ||
402
+ (context.startupCursorCprActive && canStillBeStartupCursorCpr(state)) ||
403
+ (context.pixelResolutionQueryActive && canStillBePixelResolution(state))
404
+ )
405
+ }
406
+
407
+ function canCompleteDeferredParametricCsi(
408
+ state: ParametricCsiLike,
409
+ byte: number,
410
+ context: StdinParserProtocolContext,
411
+ ): boolean {
412
+ if (context.kittyKeyboardEnabled) {
413
+ if (state.hasDigit && byte === 0x75) return true
414
+ if (
415
+ state.hasDigit &&
416
+ state.semicolons === 1 &&
417
+ state.segments > 1 &&
418
+ (byte === 0x7e || (byte >= 0x41 && byte <= 0x5a))
419
+ ) {
420
+ return true
421
+ }
422
+ }
423
+
424
+ if (
425
+ context.explicitWidthCprActive &&
426
+ state.hasDigit &&
427
+ state.firstParamValue === 1 &&
428
+ state.semicolons === 1 &&
429
+ byte === 0x52
430
+ ) {
431
+ return true
432
+ }
433
+
434
+ if (context.startupCursorCprActive && state.hasDigit && state.semicolons === 1 && byte === 0x52) {
435
+ return true
436
+ }
437
+
438
+ if (
439
+ context.pixelResolutionQueryActive &&
440
+ state.hasDigit &&
441
+ state.firstParamValue === 4 &&
442
+ state.semicolons === 2 &&
443
+ byte === 0x74
444
+ ) {
445
+ return true
446
+ }
447
+
448
+ return false
449
+ }
450
+
451
+ function classifyParametricCsiProtocol(state: ParametricCsiLike, finalByte: number): StdinResponseProtocol {
452
+ if (finalByte === 0x52 && state.semicolons === 1 && state.segments === 1 && state.hasDigit) {
453
+ return "cpr"
454
+ }
455
+
456
+ return "csi"
457
+ }
458
+
459
+ function canDeferPrivateReplyCsi(context: StdinParserProtocolContext): boolean {
460
+ return context.privateCapabilityRepliesActive
461
+ }
462
+
463
+ function canCompleteDeferredPrivateReplyCsi(
464
+ state: PrivateReplyCsiLike,
465
+ byte: number,
466
+ context: StdinParserProtocolContext,
467
+ ): boolean {
468
+ if (!context.privateCapabilityRepliesActive) return false
469
+ if (state.sawDollar) return state.hasDigit && byte === 0x79
470
+ if (byte === 0x63) return state.hasDigit || state.semicolons > 0
471
+ if (byte === 0x6e) return state.hasDigit
472
+ return state.hasDigit && byte === 0x75
473
+ }
474
+
475
+ function concatBytes(left: Uint8Array, right: Uint8Array): Uint8Array {
476
+ if (left.length === 0) {
477
+ return right
478
+ }
479
+
480
+ if (right.length === 0) {
481
+ return left
482
+ }
483
+
484
+ const combined = new Uint8Array(left.length + right.length)
485
+ combined.set(left, 0)
486
+ combined.set(right, left.length)
487
+ return combined
488
+ }
489
+
490
+ function withEscPrefix(bytes: Uint8Array): Uint8Array {
491
+ const prefixed = new Uint8Array(bytes.length + 1)
492
+ prefixed[0] = ESC
493
+ prefixed.set(bytes, 1)
494
+ return prefixed
495
+ }
496
+
497
+ function indexOfBytes(haystack: Uint8Array, needle: Uint8Array): number {
498
+ if (needle.length === 0) {
499
+ return 0
500
+ }
501
+
502
+ const limit = haystack.length - needle.length
503
+ for (let offset = 0; offset <= limit; offset += 1) {
504
+ let matched = true
505
+ for (let index = 0; index < needle.length; index += 1) {
506
+ if (haystack[offset + index] !== needle[index]) {
507
+ matched = false
508
+ break
509
+ }
510
+ }
511
+
512
+ if (matched) {
513
+ return offset
514
+ }
515
+ }
516
+
517
+ return -1
518
+ }
519
+
520
+ // Decodes raw protocol bytes as latin1. Used for mouse and response events
521
+ // where the wire bytes may not be valid UTF-8 but need a lossless string
522
+ // form for downstream sequence handlers.
523
+ function decodeLatin1(bytes: Uint8Array): string {
524
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1")
525
+ }
526
+
527
+ function decodeUtf8(bytes: Uint8Array): string {
528
+ return KEY_DECODER.decode(bytes)
529
+ }
530
+
531
+ function createPasteCollector(): PasteCollector {
532
+ return {
533
+ tail: EMPTY_BYTES,
534
+ parts: [],
535
+ totalLength: 0,
536
+ }
537
+ }
538
+
539
+ function joinPasteBytes(parts: Uint8Array[], totalLength: number): Uint8Array {
540
+ if (totalLength === 0) {
541
+ return EMPTY_BYTES
542
+ }
543
+
544
+ if (parts.length === 1) {
545
+ return parts[0]!
546
+ }
547
+
548
+ const bytes = new Uint8Array(totalLength)
549
+ let offset = 0
550
+ for (const part of parts) {
551
+ bytes.set(part, offset)
552
+ offset += part.length
553
+ }
554
+
555
+ return bytes
556
+ }
557
+
558
+ // Push-driven stdin parser. Callers feed raw bytes via push(), then read
559
+ // typed events via read() or drain(). At most one incomplete protocol unit
560
+ // is buffered at a time; everything else is immediately converted to events.
561
+ //
562
+ // The parser guarantees chunk-shape invariance: the same bytes always produce
563
+ // the same events, regardless of chunk boundaries. A lone ESC resolves via
564
+ // timeout, split UTF-8 codepoints reassemble correctly, and bracketed paste
565
+ // markers may split across any chunk boundary.
566
+ export class StdinParser {
567
+ private readonly pending = new ByteQueue(INITIAL_PENDING_CAPACITY)
568
+ private readonly events: StdinEvent[] = []
569
+ private readonly timeoutMs: number
570
+ private readonly maxPendingBytes: number
571
+ private readonly armTimeouts: boolean
572
+ private readonly onTimeoutFlush: (() => void) | null
573
+ private readonly useKittyKeyboard: boolean
574
+ private readonly mouseParser = new MouseParser()
575
+ private readonly clock: Clock
576
+ private protocolContext: StdinParserProtocolContext
577
+ private timeoutId: TimerHandle | null = null
578
+ private destroyed = false
579
+ // When the current incomplete unit first appeared. Null when nothing is pending.
580
+ private pendingSinceMs: number | null = null
581
+ // When true, the state machine treats the current incomplete prefix as
582
+ // final and emits it as one atomic event (e.g. a lone ESC becomes an
583
+ // Escape key). Set by the timeout, consumed by the next read() or drain().
584
+ private forceFlush = false
585
+ // True only immediately after a timeout flush emits a lone ESC key. The next
586
+ // `[` may begin a delayed `[<...M/m` mouse continuation recovery path.
587
+ private justFlushedEsc = false
588
+ private state: ParserState = { tag: "ground" }
589
+ // Scan position within pending.view() during scanPending().
590
+ private cursor = 0
591
+ // Start of the protocol unit currently being parsed. The bytes from
592
+ // unitStart through cursor all belong to one atomic unit.
593
+ private unitStart = 0
594
+ // When non-null, the parser is inside a bracketed paste. All incoming
595
+ // bytes flow through consumePasteBytes() instead of the normal state machine.
596
+ private paste: PasteCollector | null = null
597
+
598
+ constructor(options: StdinParserOptions = {}) {
599
+ this.timeoutMs = normalizePositiveOption(options.timeoutMs, DEFAULT_TIMEOUT_MS)
600
+ this.maxPendingBytes = normalizePositiveOption(options.maxPendingBytes, DEFAULT_MAX_PENDING_BYTES)
601
+ this.armTimeouts = options.armTimeouts ?? true
602
+ this.onTimeoutFlush = options.onTimeoutFlush ?? null
603
+ this.useKittyKeyboard = options.useKittyKeyboard ?? true
604
+ this.clock = options.clock ?? SYSTEM_CLOCK
605
+ this.protocolContext = {
606
+ ...DEFAULT_PROTOCOL_CONTEXT,
607
+ kittyKeyboardEnabled: options.protocolContext?.kittyKeyboardEnabled ?? false,
608
+ privateCapabilityRepliesActive: options.protocolContext?.privateCapabilityRepliesActive ?? false,
609
+ pixelResolutionQueryActive: options.protocolContext?.pixelResolutionQueryActive ?? false,
610
+ explicitWidthCprActive: options.protocolContext?.explicitWidthCprActive ?? false,
611
+ startupCursorCprActive: options.protocolContext?.startupCursorCprActive ?? false,
612
+ }
613
+ }
614
+
615
+ public get bufferCapacity(): number {
616
+ return this.pending.capacity
617
+ }
618
+
619
+ public updateProtocolContext(patch: Partial<StdinParserProtocolContext>): void {
620
+ this.ensureAlive()
621
+ this.protocolContext = { ...this.protocolContext, ...patch }
622
+ this.reconcileDeferredStateWithProtocolContext()
623
+ this.reconcileTimeoutState()
624
+ }
625
+
626
+ // A startup CPR can be split either after `ESC[` or after the first `;`.
627
+ // Normalize both shapes into one ignore-state so leaving split-footer can
628
+ // cancel the stale reply without also swallowing unrelated CSI sequences.
629
+ private getAbortableStartupCursorCprState(): Extract<ParserState, { tag: "csi_parametric_ignored" }> | null {
630
+ if (this.pending.length === 0) {
631
+ return null
632
+ }
633
+
634
+ switch (this.state.tag) {
635
+ case "csi": {
636
+ const bytes = this.pending.view()
637
+ const firstParamStart = this.unitStart + 2
638
+ if (this.cursor < firstParamStart) {
639
+ return null
640
+ }
641
+
642
+ let firstParamValue: number | null = null
643
+ for (let index = firstParamStart; index < this.cursor; index += 1) {
644
+ const byte = bytes[index]!
645
+ if (!isAsciiDigit(byte)) {
646
+ return null
647
+ }
648
+
649
+ firstParamValue = (firstParamValue ?? 0) * 10 + (byte - 0x30)
650
+ }
651
+
652
+ return {
653
+ tag: "csi_parametric_ignored",
654
+ semicolons: 0,
655
+ segments: 1,
656
+ hasDigit: this.cursor > firstParamStart,
657
+ firstParamValue,
658
+ }
659
+ }
660
+
661
+ case "csi_parametric":
662
+ case "csi_parametric_deferred":
663
+ if (
664
+ !canStillBeStartupCursorCprPrefix(this.state) ||
665
+ (this.protocolContext.explicitWidthCprActive && canStillBeExplicitWidthCpr(this.state))
666
+ ) {
667
+ return null
668
+ }
669
+
670
+ return {
671
+ tag: "csi_parametric_ignored",
672
+ semicolons: this.state.semicolons,
673
+ segments: this.state.segments,
674
+ hasDigit: this.state.hasDigit,
675
+ firstParamValue: this.state.firstParamValue,
676
+ }
677
+ }
678
+
679
+ return null
680
+ }
681
+
682
+ public abortPendingStartupCursorCpr(): void {
683
+ this.ensureAlive()
684
+
685
+ const nextState = this.getAbortableStartupCursorCprState()
686
+ if (!nextState) {
687
+ return
688
+ }
689
+
690
+ this.state = nextState
691
+
692
+ if (this.pendingSinceMs === null) {
693
+ this.markPending()
694
+ }
695
+
696
+ this.forceFlush = false
697
+ this.reconcileTimeoutState()
698
+ }
699
+
700
+ // Feeds raw stdin bytes into the parser. Converts as much as possible into
701
+ // queued events and leaves at most one incomplete unit behind in pending.
702
+ //
703
+ // When a chunk contains a paste start marker, bytes before the marker go
704
+ // through normal parsing, then paste mode takes over for the rest. This
705
+ // prevents large pastes from growing the main buffer.
706
+ public push(data: Uint8Array): void {
707
+ this.ensureAlive()
708
+ if (data.length === 0) {
709
+ // Preserve the existing empty-chunk -> empty-keypress behavior.
710
+ this.emitKeyOrResponse("unknown", "")
711
+ return
712
+ }
713
+
714
+ let remainder = data
715
+ while (remainder.length > 0) {
716
+ if (this.paste) {
717
+ remainder = this.consumePasteBytes(remainder)
718
+ continue
719
+ }
720
+
721
+ // If we're in ground state with nothing pending, scan the incoming
722
+ // chunk for a paste start marker. Only append through the marker so
723
+ // scanPending() enters paste mode without buffering the full paste.
724
+ const immediatePasteStartIndex =
725
+ this.state.tag === "ground" && this.pending.length === 0 ? indexOfBytes(remainder, BRACKETED_PASTE_START) : -1
726
+ const appendEnd =
727
+ immediatePasteStartIndex === -1 ? remainder.length : immediatePasteStartIndex + BRACKETED_PASTE_START.length
728
+
729
+ this.pending.append(remainder.subarray(0, appendEnd))
730
+ remainder = remainder.subarray(appendEnd)
731
+ this.scanPending()
732
+
733
+ if (this.paste && this.pending.length > 0) {
734
+ remainder = this.consumePasteBytes(this.takePendingBytes())
735
+ continue
736
+ }
737
+
738
+ if (!this.paste && this.pending.length > this.maxPendingBytes) {
739
+ this.flushPendingOverflow()
740
+ this.scanPending()
741
+
742
+ if (this.paste && this.pending.length > 0) {
743
+ remainder = this.consumePasteBytes(this.takePendingBytes())
744
+ }
745
+ }
746
+ }
747
+
748
+ this.reconcileTimeoutState()
749
+ }
750
+
751
+ // Pops one event from the queue. If the queue is empty and a timeout has
752
+ // set forceFlush, re-scans pending to convert the timed-out incomplete
753
+ // unit into one final event before returning it.
754
+ public read(): StdinEvent | null {
755
+ this.ensureAlive()
756
+
757
+ if (this.events.length === 0 && this.forceFlush) {
758
+ this.scanPending()
759
+ this.reconcileTimeoutState()
760
+ }
761
+
762
+ return this.events.shift() ?? null
763
+ }
764
+
765
+ // Delivers all queued events. Stops early if the parser is destroyed
766
+ // during a callback (e.g. an event handler triggers teardown).
767
+ public drain(onEvent: (event: StdinEvent) => void): void {
768
+ this.ensureAlive()
769
+
770
+ while (true) {
771
+ if (this.destroyed) {
772
+ return
773
+ }
774
+
775
+ const event = this.read()
776
+ if (!event) {
777
+ return
778
+ }
779
+
780
+ onEvent(event)
781
+ }
782
+ }
783
+
784
+ // Marks the parser for forced flush if enough time has passed since
785
+ // incomplete data arrived. Does not immediately emit events — the next
786
+ // read() or drain() does the actual flush. This separation keeps the
787
+ // timer callback from emitting events mid-flight in user code.
788
+ public flushTimeout(nowMsValue: number = this.clock.now()): void {
789
+ this.ensureAlive()
790
+
791
+ if (
792
+ this.pendingSinceMs !== null &&
793
+ (nowMsValue < this.pendingSinceMs || nowMsValue - this.pendingSinceMs < this.timeoutMs)
794
+ ) {
795
+ return
796
+ }
797
+
798
+ this.tryForceFlush()
799
+ }
800
+
801
+ // Sets forceFlush when there are pending bytes outside of a paste.
802
+ // Extracted so the setTimeout callback in reconcileTimeoutState() can
803
+ // bypass flushTimeout()'s elapsed-time comparison. Timer scheduling and
804
+ // clock.now() sampling can disagree by a small amount; re-checking elapsed
805
+ // time in the callback can skip a flush and leave pending bytes stuck.
806
+ private tryForceFlush(): void {
807
+ if (this.paste || this.pendingSinceMs === null || this.pending.length === 0) {
808
+ return
809
+ }
810
+
811
+ this.forceFlush = true
812
+ }
813
+
814
+ public reset(): void {
815
+ if (this.destroyed) {
816
+ return
817
+ }
818
+
819
+ this.clearTimeout()
820
+ this.resetState()
821
+ }
822
+
823
+ public resetMouseState(): void {
824
+ this.ensureAlive()
825
+ this.mouseParser.reset()
826
+ }
827
+
828
+ public destroy(): void {
829
+ if (this.destroyed) {
830
+ return
831
+ }
832
+
833
+ this.clearTimeout()
834
+ this.destroyed = true
835
+ this.resetState()
836
+ }
837
+
838
+ private ensureAlive(): void {
839
+ if (this.destroyed) {
840
+ throw new Error("StdinParser has been destroyed")
841
+ }
842
+ }
843
+
844
+ // Scans the pending byte buffer one byte at a time, dispatching on the
845
+ // current parser state. All protocol framing lives in this single switch
846
+ // — intentionally not split into per-mode scan helpers.
847
+ //
848
+ // Exits when: all bytes consumed (ground), more bytes needed (incomplete
849
+ // unit), or paste mode entered (body handled by consumePasteBytes).
850
+ private scanPending(): void {
851
+ while (!this.paste) {
852
+ const bytes = this.pending.view()
853
+ if (this.state.tag === "ground" && this.cursor >= bytes.length) {
854
+ this.pending.clear()
855
+ this.cursor = 0
856
+ this.unitStart = 0
857
+ this.pendingSinceMs = null
858
+ this.forceFlush = false
859
+ return
860
+ }
861
+
862
+ const byte = this.cursor < bytes.length ? bytes[this.cursor]! : -1
863
+ switch (this.state.tag) {
864
+ case "ground": {
865
+ this.unitStart = this.cursor
866
+
867
+ // After a timeout-flushed lone ESC, a following `[` may be the start
868
+ // of a delayed `[<...M/m` mouse continuation. Recover only this narrow
869
+ // case; otherwise clear the recovery flag and parse bytes normally.
870
+ if (this.justFlushedEsc) {
871
+ if (byte === 0x5b) {
872
+ this.justFlushedEsc = false
873
+ this.cursor += 1
874
+ this.state = { tag: "esc_recovery" }
875
+ continue
876
+ }
877
+
878
+ this.justFlushedEsc = false
879
+ }
880
+
881
+ if (byte === ESC) {
882
+ this.cursor += 1
883
+ this.state = { tag: "esc" }
884
+ continue
885
+ }
886
+
887
+ if (byte < 0x80) {
888
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.cursor, this.cursor + 1)))
889
+ this.consumePrefix(this.cursor + 1)
890
+ continue
891
+ }
892
+
893
+ // Invalid UTF-8 lead byte. Could be a legacy high-byte from an
894
+ // older terminal. If it's the last byte in the buffer, wait for
895
+ // more data or a timeout before committing. On timeout, emit
896
+ // through parseKeypress() which handles meta-key behavior.
897
+ const expected = utf8SequenceLength(byte)
898
+ if (expected === 0) {
899
+ if (!this.forceFlush && this.cursor + 1 === bytes.length) {
900
+ this.markPending()
901
+ return
902
+ }
903
+
904
+ this.emitLegacyHighByte(byte)
905
+ this.consumePrefix(this.cursor + 1)
906
+ continue
907
+ }
908
+
909
+ this.cursor += 1
910
+ this.state = { tag: "utf8", expected, seen: 1 }
911
+ continue
912
+ }
913
+
914
+ case "utf8": {
915
+ if (this.cursor >= bytes.length) {
916
+ if (!this.forceFlush) {
917
+ this.markPending()
918
+ return
919
+ }
920
+
921
+ this.emitLegacyHighByte(bytes[this.unitStart]!)
922
+ this.state = { tag: "ground" }
923
+ this.consumePrefix(this.unitStart + 1)
924
+ continue
925
+ }
926
+
927
+ // Not a valid continuation byte. Treat the lead byte as a legacy
928
+ // high-byte character and restart parsing from this position.
929
+ if ((byte & 0xc0) !== 0x80) {
930
+ this.emitLegacyHighByte(bytes[this.unitStart]!)
931
+ this.state = { tag: "ground" }
932
+ this.consumePrefix(this.unitStart + 1)
933
+ continue
934
+ }
935
+
936
+ const nextSeen = this.state.seen + 1
937
+ this.cursor += 1
938
+ if (nextSeen < this.state.expected) {
939
+ this.state = { tag: "utf8", expected: this.state.expected, seen: nextSeen }
940
+ continue
941
+ }
942
+
943
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.cursor)))
944
+ this.state = { tag: "ground" }
945
+ this.consumePrefix(this.cursor)
946
+ continue
947
+ }
948
+
949
+ case "esc": {
950
+ if (this.cursor >= bytes.length) {
951
+ if (!this.forceFlush) {
952
+ this.markPending()
953
+ return
954
+ }
955
+
956
+ const flushedLoneEsc = this.cursor === this.unitStart + 1 && bytes[this.unitStart] === ESC
957
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.cursor)))
958
+ this.justFlushedEsc = flushedLoneEsc
959
+ this.state = { tag: "ground" }
960
+ this.consumePrefix(this.cursor)
961
+ continue
962
+ }
963
+
964
+ // The byte after ESC determines the sub-protocol:
965
+ // [ -> CSI, O -> SS3, ] -> OSC, P -> DCS, _ -> APC.
966
+ switch (byte) {
967
+ case 0x5b:
968
+ this.cursor += 1
969
+ this.state = { tag: "csi" }
970
+ continue
971
+ case 0x4f:
972
+ this.cursor += 1
973
+ this.state = { tag: "ss3" }
974
+ continue
975
+ case 0x5d:
976
+ this.cursor += 1
977
+ this.state = { tag: "osc", sawEsc: false }
978
+ continue
979
+ case 0x50:
980
+ this.cursor += 1
981
+ this.state = { tag: "dcs", sawEsc: false }
982
+ continue
983
+ case 0x5f:
984
+ this.cursor += 1
985
+ this.state = { tag: "apc", sawEsc: false }
986
+ continue
987
+ // ESC ESC: stay in esc state. Terminals encode Alt+ESC and
988
+ // similar sequences as ESC ESC [...], so we keep scanning.
989
+ case ESC:
990
+ this.cursor += 1
991
+ continue
992
+ default:
993
+ this.cursor += 1
994
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.cursor)))
995
+ this.state = { tag: "ground" }
996
+ this.consumePrefix(this.cursor)
997
+ continue
998
+ }
999
+ }
1000
+
1001
+ case "ss3": {
1002
+ if (this.cursor >= bytes.length) {
1003
+ if (!this.forceFlush) {
1004
+ this.markPending()
1005
+ return
1006
+ }
1007
+
1008
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1009
+ this.state = { tag: "ground" }
1010
+ this.consumePrefix(this.cursor)
1011
+ continue
1012
+ }
1013
+
1014
+ if (byte === ESC) {
1015
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1016
+ this.state = { tag: "ground" }
1017
+ this.consumePrefix(this.cursor)
1018
+ continue
1019
+ }
1020
+
1021
+ this.cursor += 1
1022
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.cursor)))
1023
+ this.state = { tag: "ground" }
1024
+ this.consumePrefix(this.cursor)
1025
+ continue
1026
+ }
1027
+
1028
+ // Narrow recovery path for delayed mouse continuations after a
1029
+ // timeout-flushed lone ESC. Wait for either `<` (SGR) or `M` (X10); if
1030
+ // neither arrives, flush `[` as a normal key.
1031
+ case "esc_recovery": {
1032
+ if (this.cursor >= bytes.length) {
1033
+ if (!this.forceFlush) {
1034
+ this.markPending()
1035
+ return
1036
+ }
1037
+
1038
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.cursor)))
1039
+ this.state = { tag: "ground" }
1040
+ this.consumePrefix(this.cursor)
1041
+ continue
1042
+ }
1043
+
1044
+ if (byte === 0x3c) {
1045
+ this.cursor += 1
1046
+ this.state = { tag: "esc_less_mouse" }
1047
+ continue
1048
+ }
1049
+
1050
+ if (byte === 0x4d) {
1051
+ this.cursor += 1
1052
+ this.state = { tag: "esc_less_x10_mouse" }
1053
+ continue
1054
+ }
1055
+
1056
+ this.emitKeyOrResponse("unknown", decodeUtf8(bytes.subarray(this.unitStart, this.unitStart + 1)))
1057
+ this.state = { tag: "ground" }
1058
+ this.consumePrefix(this.unitStart + 1)
1059
+ continue
1060
+ }
1061
+
1062
+ case "csi": {
1063
+ if (this.cursor >= bytes.length) {
1064
+ if (!this.forceFlush) {
1065
+ this.markPending()
1066
+ return
1067
+ }
1068
+
1069
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1070
+ this.state = { tag: "ground" }
1071
+ this.consumePrefix(this.cursor)
1072
+ continue
1073
+ }
1074
+
1075
+ // A new ESC inside an incomplete CSI means the previous sequence
1076
+ // was interrupted. Flush everything before the new ESC as one
1077
+ // opaque response, then restart parsing at the new ESC.
1078
+ if (byte === ESC) {
1079
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1080
+ this.state = { tag: "ground" }
1081
+ this.consumePrefix(this.cursor)
1082
+ continue
1083
+ }
1084
+
1085
+ // X10 mouse: ESC [ M plus 3 raw payload bytes (button, x, y).
1086
+ // cursor === unitStart + 2 confirms M comes right after ESC[,
1087
+ // not as a later final byte in a different CSI sequence.
1088
+ if (byte === 0x4d && this.cursor === this.unitStart + 2) {
1089
+ const end = this.cursor + 4
1090
+ if (bytes.length < end) {
1091
+ if (!this.forceFlush) {
1092
+ this.markPending()
1093
+ return
1094
+ }
1095
+
1096
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, bytes.length))
1097
+ this.state = { tag: "ground" }
1098
+ this.consumePrefix(bytes.length)
1099
+ continue
1100
+ }
1101
+
1102
+ this.emitMouse(bytes.subarray(this.unitStart, end), "x10")
1103
+ this.state = { tag: "ground" }
1104
+ this.consumePrefix(end)
1105
+ continue
1106
+ }
1107
+
1108
+ if (byte === 0x24) {
1109
+ const candidateEnd = this.cursor + 1
1110
+ const candidate = decodeUtf8(bytes.subarray(this.unitStart, candidateEnd))
1111
+ if (RXVT_DOLLAR_CSI_RE.test(candidate)) {
1112
+ this.emitKeyOrResponse("csi", candidate)
1113
+ this.state = { tag: "ground" }
1114
+ this.consumePrefix(candidateEnd)
1115
+ continue
1116
+ }
1117
+
1118
+ if (!this.forceFlush && candidateEnd >= bytes.length) {
1119
+ this.markPending()
1120
+ return
1121
+ }
1122
+ }
1123
+
1124
+ if (byte === 0x3c && this.cursor === this.unitStart + 2) {
1125
+ this.cursor += 1
1126
+ this.state = { tag: "csi_sgr_mouse", part: 0, hasDigit: false }
1127
+ continue
1128
+ }
1129
+
1130
+ // Some terminals use ESC [[A..E / ESC [[5~ / ESC [[6~ variants.
1131
+ // Treat the second `[` immediately after ESC[ as part of the CSI
1132
+ // payload instead of as a final byte so parseKeypress() can match
1133
+ // `[[A`, `[[B`, `[[5~`, etc.
1134
+ if (byte === 0x5b && this.cursor === this.unitStart + 2) {
1135
+ this.cursor += 1
1136
+ continue
1137
+ }
1138
+
1139
+ if (byte === 0x3f && this.cursor === this.unitStart + 2) {
1140
+ this.cursor += 1
1141
+ this.state = { tag: "csi_private_reply", semicolons: 0, hasDigit: false, sawDollar: false }
1142
+ continue
1143
+ }
1144
+
1145
+ if (byte === 0x3b) {
1146
+ const firstParamStart = this.unitStart + 2
1147
+ const firstParamEnd = this.cursor
1148
+ let firstParamValue = parsePositiveDecimalPrefix(bytes, firstParamStart, firstParamEnd)
1149
+
1150
+ if (firstParamValue === null && this.protocolContext.kittyKeyboardEnabled) {
1151
+ firstParamValue = parseKittyFirstFieldCodepoint(bytes, firstParamStart, firstParamEnd)
1152
+ }
1153
+
1154
+ if (firstParamValue !== null) {
1155
+ this.cursor += 1
1156
+ this.state = {
1157
+ tag: "csi_parametric",
1158
+ semicolons: 1,
1159
+ segments: 1,
1160
+ hasDigit: false,
1161
+ firstParamValue,
1162
+ }
1163
+ continue
1164
+ }
1165
+ }
1166
+
1167
+ // Standard CSI final byte (0x40–0x7E). Check for bracketed paste
1168
+ // start, SGR mouse, or a regular CSI key/response.
1169
+ if (byte >= 0x40 && byte <= 0x7e) {
1170
+ const end = this.cursor + 1
1171
+ const rawBytes = bytes.subarray(this.unitStart, end)
1172
+
1173
+ if (bytesEqual(rawBytes, BRACKETED_PASTE_START)) {
1174
+ this.state = { tag: "ground" }
1175
+ this.consumePrefix(end)
1176
+ this.paste = createPasteCollector()
1177
+ continue
1178
+ }
1179
+
1180
+ if (isMouseSgrSequence(rawBytes)) {
1181
+ this.emitMouse(rawBytes, "sgr")
1182
+ this.state = { tag: "ground" }
1183
+ this.consumePrefix(end)
1184
+ continue
1185
+ }
1186
+
1187
+ this.emitKeyOrResponse("csi", decodeUtf8(rawBytes))
1188
+ this.state = { tag: "ground" }
1189
+ this.consumePrefix(end)
1190
+ continue
1191
+ }
1192
+
1193
+ this.cursor += 1
1194
+ continue
1195
+ }
1196
+
1197
+ case "csi_sgr_mouse": {
1198
+ if (this.cursor >= bytes.length) {
1199
+ if (!this.forceFlush) {
1200
+ this.markPending()
1201
+ return
1202
+ }
1203
+
1204
+ this.state = { tag: "csi_sgr_mouse_deferred", part: this.state.part, hasDigit: this.state.hasDigit }
1205
+ this.pendingSinceMs = null
1206
+ this.forceFlush = false
1207
+ return
1208
+ }
1209
+
1210
+ if (byte === ESC) {
1211
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1212
+ this.state = { tag: "ground" }
1213
+ this.consumePrefix(this.cursor)
1214
+ continue
1215
+ }
1216
+
1217
+ if (isAsciiDigit(byte)) {
1218
+ this.cursor += 1
1219
+ this.state = { tag: "csi_sgr_mouse", part: this.state.part, hasDigit: true }
1220
+ continue
1221
+ }
1222
+
1223
+ if (byte === 0x3b && this.state.hasDigit && this.state.part < 2) {
1224
+ this.cursor += 1
1225
+ this.state = { tag: "csi_sgr_mouse", part: this.state.part + 1, hasDigit: false }
1226
+ continue
1227
+ }
1228
+
1229
+ if (byte >= 0x40 && byte <= 0x7e) {
1230
+ const end = this.cursor + 1
1231
+ const rawBytes = bytes.subarray(this.unitStart, end)
1232
+ if (isMouseSgrSequence(rawBytes)) {
1233
+ this.emitMouse(rawBytes, "sgr")
1234
+ } else {
1235
+ this.emitKeyOrResponse("csi", decodeUtf8(rawBytes))
1236
+ }
1237
+ this.state = { tag: "ground" }
1238
+ this.consumePrefix(end)
1239
+ continue
1240
+ }
1241
+
1242
+ this.state = { tag: "csi" }
1243
+ continue
1244
+ }
1245
+
1246
+ case "csi_sgr_mouse_deferred": {
1247
+ if (this.cursor >= bytes.length) {
1248
+ this.pendingSinceMs = null
1249
+ this.forceFlush = false
1250
+ return
1251
+ }
1252
+
1253
+ if (byte === ESC) {
1254
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1255
+ this.state = { tag: "ground" }
1256
+ this.consumePrefix(this.cursor)
1257
+ continue
1258
+ }
1259
+
1260
+ if (isAsciiDigit(byte) || byte === 0x3b || byte === 0x4d || byte === 0x6d) {
1261
+ this.state = { tag: "csi_sgr_mouse", part: this.state.part, hasDigit: this.state.hasDigit }
1262
+ continue
1263
+ }
1264
+
1265
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1266
+ this.state = { tag: "ground" }
1267
+ this.consumePrefix(this.cursor)
1268
+ continue
1269
+ }
1270
+
1271
+ case "csi_parametric": {
1272
+ if (this.cursor >= bytes.length) {
1273
+ if (!this.forceFlush) {
1274
+ this.markPending()
1275
+ return
1276
+ }
1277
+
1278
+ if (canDeferParametricCsi(this.state, this.protocolContext)) {
1279
+ this.state = {
1280
+ tag: "csi_parametric_deferred",
1281
+ semicolons: this.state.semicolons,
1282
+ segments: this.state.segments,
1283
+ hasDigit: this.state.hasDigit,
1284
+ firstParamValue: this.state.firstParamValue,
1285
+ }
1286
+ this.pendingSinceMs = null
1287
+ this.forceFlush = false
1288
+ return
1289
+ }
1290
+
1291
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1292
+ this.state = { tag: "ground" }
1293
+ this.consumePrefix(this.cursor)
1294
+ continue
1295
+ }
1296
+
1297
+ if (byte === ESC) {
1298
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1299
+ this.state = { tag: "ground" }
1300
+ this.consumePrefix(this.cursor)
1301
+ continue
1302
+ }
1303
+
1304
+ if (isAsciiDigit(byte)) {
1305
+ this.cursor += 1
1306
+ this.state = {
1307
+ tag: "csi_parametric",
1308
+ semicolons: this.state.semicolons,
1309
+ segments: this.state.segments,
1310
+ hasDigit: true,
1311
+ firstParamValue: this.state.firstParamValue,
1312
+ }
1313
+ continue
1314
+ }
1315
+
1316
+ if (byte === 0x3a && this.state.hasDigit && this.state.segments < 3) {
1317
+ this.cursor += 1
1318
+ this.state = {
1319
+ tag: "csi_parametric",
1320
+ semicolons: this.state.semicolons,
1321
+ segments: this.state.segments + 1,
1322
+ hasDigit: false,
1323
+ firstParamValue: this.state.firstParamValue,
1324
+ }
1325
+ continue
1326
+ }
1327
+
1328
+ if (byte === 0x3b && this.state.semicolons < 2) {
1329
+ this.cursor += 1
1330
+ this.state = {
1331
+ tag: "csi_parametric",
1332
+ semicolons: this.state.semicolons + 1,
1333
+ segments: 1,
1334
+ hasDigit: false,
1335
+ firstParamValue: this.state.firstParamValue,
1336
+ }
1337
+ continue
1338
+ }
1339
+
1340
+ if (byte >= 0x40 && byte <= 0x7e) {
1341
+ const end = this.cursor + 1
1342
+ const protocol = classifyParametricCsiProtocol(this.state, byte)
1343
+ this.emitKeyOrResponse(protocol, decodeUtf8(bytes.subarray(this.unitStart, end)))
1344
+ this.state = { tag: "ground" }
1345
+ this.consumePrefix(end)
1346
+ continue
1347
+ }
1348
+
1349
+ this.state = { tag: "csi" }
1350
+ continue
1351
+ }
1352
+
1353
+ case "csi_parametric_deferred": {
1354
+ if (this.cursor >= bytes.length) {
1355
+ this.pendingSinceMs = null
1356
+ this.forceFlush = false
1357
+ return
1358
+ }
1359
+
1360
+ if (byte === ESC) {
1361
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1362
+ this.state = { tag: "ground" }
1363
+ this.consumePrefix(this.cursor)
1364
+ continue
1365
+ }
1366
+
1367
+ if (isAsciiDigit(byte) || byte === 0x3a || byte === 0x3b) {
1368
+ this.state = {
1369
+ tag: "csi_parametric",
1370
+ semicolons: this.state.semicolons,
1371
+ segments: this.state.segments,
1372
+ hasDigit: this.state.hasDigit,
1373
+ firstParamValue: this.state.firstParamValue,
1374
+ }
1375
+ continue
1376
+ }
1377
+
1378
+ if (canCompleteDeferredParametricCsi(this.state, byte, this.protocolContext)) {
1379
+ this.state = {
1380
+ tag: "csi_parametric",
1381
+ semicolons: this.state.semicolons,
1382
+ segments: this.state.segments,
1383
+ hasDigit: this.state.hasDigit,
1384
+ firstParamValue: this.state.firstParamValue,
1385
+ }
1386
+ continue
1387
+ }
1388
+
1389
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1390
+ this.state = { tag: "ground" }
1391
+ this.consumePrefix(this.cursor)
1392
+ continue
1393
+ }
1394
+
1395
+ case "csi_parametric_ignored": {
1396
+ if (this.cursor >= bytes.length) {
1397
+ if (!this.forceFlush) {
1398
+ this.markPending()
1399
+ return
1400
+ }
1401
+
1402
+ this.state = { tag: "ground" }
1403
+ this.consumePrefix(this.cursor)
1404
+ continue
1405
+ }
1406
+
1407
+ if (byte === ESC) {
1408
+ this.state = { tag: "ground" }
1409
+ this.consumePrefix(this.cursor)
1410
+ continue
1411
+ }
1412
+
1413
+ if (isAsciiDigit(byte)) {
1414
+ this.cursor += 1
1415
+ this.state = {
1416
+ tag: "csi_parametric_ignored",
1417
+ semicolons: this.state.semicolons,
1418
+ segments: this.state.segments,
1419
+ hasDigit: true,
1420
+ firstParamValue:
1421
+ this.state.semicolons === 0
1422
+ ? (this.state.firstParamValue ?? 0) * 10 + (byte - 0x30)
1423
+ : this.state.firstParamValue,
1424
+ }
1425
+ continue
1426
+ }
1427
+
1428
+ if (byte === 0x3b && this.state.semicolons === 0 && this.state.hasDigit) {
1429
+ // `CSI 1;...R` is also used by the explicit-width probe, so once we
1430
+ // learn that first param we must hand control back to normal CSI
1431
+ // parsing instead of discarding the rest of the reply.
1432
+ if (this.protocolContext.explicitWidthCprActive && this.state.firstParamValue === 1) {
1433
+ this.state = { tag: "csi" }
1434
+ continue
1435
+ }
1436
+
1437
+ this.cursor += 1
1438
+ this.state = {
1439
+ tag: "csi_parametric_ignored",
1440
+ semicolons: 1,
1441
+ segments: 1,
1442
+ hasDigit: false,
1443
+ firstParamValue: this.state.firstParamValue,
1444
+ }
1445
+ continue
1446
+ }
1447
+
1448
+ if (byte === 0x52 && this.state.semicolons === 1 && this.state.hasDigit) {
1449
+ const end = this.cursor + 1
1450
+ this.state = { tag: "ground" }
1451
+ this.consumePrefix(end)
1452
+ continue
1453
+ }
1454
+
1455
+ if (this.state.semicolons === 0) {
1456
+ this.state = { tag: "csi" }
1457
+ continue
1458
+ }
1459
+
1460
+ this.state = { tag: "ground" }
1461
+ this.consumePrefix(this.cursor)
1462
+ continue
1463
+ }
1464
+
1465
+ case "csi_private_reply": {
1466
+ if (this.cursor >= bytes.length) {
1467
+ if (!this.forceFlush) {
1468
+ this.markPending()
1469
+ return
1470
+ }
1471
+
1472
+ if (canDeferPrivateReplyCsi(this.protocolContext)) {
1473
+ this.state = {
1474
+ tag: "csi_private_reply_deferred",
1475
+ semicolons: this.state.semicolons,
1476
+ hasDigit: this.state.hasDigit,
1477
+ sawDollar: this.state.sawDollar,
1478
+ }
1479
+ this.pendingSinceMs = null
1480
+ this.forceFlush = false
1481
+ return
1482
+ }
1483
+
1484
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1485
+ this.state = { tag: "ground" }
1486
+ this.consumePrefix(this.cursor)
1487
+ continue
1488
+ }
1489
+
1490
+ if (byte === ESC) {
1491
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1492
+ this.state = { tag: "ground" }
1493
+ this.consumePrefix(this.cursor)
1494
+ continue
1495
+ }
1496
+
1497
+ if (isAsciiDigit(byte)) {
1498
+ this.cursor += 1
1499
+ this.state = {
1500
+ tag: "csi_private_reply",
1501
+ semicolons: this.state.semicolons,
1502
+ hasDigit: true,
1503
+ sawDollar: this.state.sawDollar,
1504
+ }
1505
+ continue
1506
+ }
1507
+
1508
+ if (byte === 0x3b) {
1509
+ this.cursor += 1
1510
+ this.state = {
1511
+ tag: "csi_private_reply",
1512
+ semicolons: this.state.semicolons + 1,
1513
+ hasDigit: false,
1514
+ sawDollar: false,
1515
+ }
1516
+ continue
1517
+ }
1518
+
1519
+ if (byte === 0x24 && this.state.hasDigit && !this.state.sawDollar) {
1520
+ this.cursor += 1
1521
+ this.state = {
1522
+ tag: "csi_private_reply",
1523
+ semicolons: this.state.semicolons,
1524
+ hasDigit: true,
1525
+ sawDollar: true,
1526
+ }
1527
+ continue
1528
+ }
1529
+
1530
+ if (byte >= 0x40 && byte <= 0x7e) {
1531
+ const end = this.cursor + 1
1532
+ this.emitOpaqueResponse("csi", bytes.subarray(this.unitStart, end))
1533
+ this.state = { tag: "ground" }
1534
+ this.consumePrefix(end)
1535
+ continue
1536
+ }
1537
+
1538
+ this.state = { tag: "csi" }
1539
+ continue
1540
+ }
1541
+
1542
+ case "csi_private_reply_deferred": {
1543
+ if (this.cursor >= bytes.length) {
1544
+ this.pendingSinceMs = null
1545
+ this.forceFlush = false
1546
+ return
1547
+ }
1548
+
1549
+ if (byte === ESC) {
1550
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1551
+ this.state = { tag: "ground" }
1552
+ this.consumePrefix(this.cursor)
1553
+ continue
1554
+ }
1555
+
1556
+ if (isAsciiDigit(byte) || byte === 0x3b || byte === 0x24) {
1557
+ this.state = {
1558
+ tag: "csi_private_reply",
1559
+ semicolons: this.state.semicolons,
1560
+ hasDigit: this.state.hasDigit,
1561
+ sawDollar: this.state.sawDollar,
1562
+ }
1563
+ continue
1564
+ }
1565
+
1566
+ if (canCompleteDeferredPrivateReplyCsi(this.state, byte, this.protocolContext)) {
1567
+ this.state = {
1568
+ tag: "csi_private_reply",
1569
+ semicolons: this.state.semicolons,
1570
+ hasDigit: this.state.hasDigit,
1571
+ sawDollar: this.state.sawDollar,
1572
+ }
1573
+ continue
1574
+ }
1575
+
1576
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1577
+ this.state = { tag: "ground" }
1578
+ this.consumePrefix(this.cursor)
1579
+ continue
1580
+ }
1581
+
1582
+ // OSC sequences end at BEL or ESC \. DCS and APC end at ESC \
1583
+ // only. The sawEsc flag tracks whether the previous byte was ESC,
1584
+ // since the two-byte ESC \ can split across push() calls.
1585
+ case "osc": {
1586
+ if (this.cursor >= bytes.length) {
1587
+ if (!this.forceFlush) {
1588
+ this.markPending()
1589
+ return
1590
+ }
1591
+
1592
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1593
+ this.state = { tag: "ground" }
1594
+ this.consumePrefix(this.cursor)
1595
+ continue
1596
+ }
1597
+
1598
+ if (this.state.sawEsc) {
1599
+ if (byte === 0x5c) {
1600
+ const end = this.cursor + 1
1601
+ this.emitOpaqueResponse("osc", bytes.subarray(this.unitStart, end))
1602
+ this.state = { tag: "ground" }
1603
+ this.consumePrefix(end)
1604
+ continue
1605
+ }
1606
+
1607
+ this.state = { tag: "osc", sawEsc: false }
1608
+ continue
1609
+ }
1610
+
1611
+ if (byte === BEL) {
1612
+ const end = this.cursor + 1
1613
+ this.emitOpaqueResponse("osc", bytes.subarray(this.unitStart, end))
1614
+ this.state = { tag: "ground" }
1615
+ this.consumePrefix(end)
1616
+ continue
1617
+ }
1618
+
1619
+ if (byte === ESC) {
1620
+ this.cursor += 1
1621
+ this.state = { tag: "osc", sawEsc: true }
1622
+ continue
1623
+ }
1624
+
1625
+ this.cursor += 1
1626
+ continue
1627
+ }
1628
+
1629
+ case "dcs": {
1630
+ if (this.cursor >= bytes.length) {
1631
+ if (!this.forceFlush) {
1632
+ this.markPending()
1633
+ return
1634
+ }
1635
+
1636
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1637
+ this.state = { tag: "ground" }
1638
+ this.consumePrefix(this.cursor)
1639
+ continue
1640
+ }
1641
+
1642
+ if (this.state.sawEsc) {
1643
+ if (byte === 0x5c) {
1644
+ const end = this.cursor + 1
1645
+ this.emitOpaqueResponse("dcs", bytes.subarray(this.unitStart, end))
1646
+ this.state = { tag: "ground" }
1647
+ this.consumePrefix(end)
1648
+ continue
1649
+ }
1650
+
1651
+ this.state = { tag: "dcs", sawEsc: false }
1652
+ continue
1653
+ }
1654
+
1655
+ if (byte === ESC) {
1656
+ this.cursor += 1
1657
+ this.state = { tag: "dcs", sawEsc: true }
1658
+ continue
1659
+ }
1660
+
1661
+ this.cursor += 1
1662
+ continue
1663
+ }
1664
+
1665
+ case "apc": {
1666
+ if (this.cursor >= bytes.length) {
1667
+ if (!this.forceFlush) {
1668
+ this.markPending()
1669
+ return
1670
+ }
1671
+
1672
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1673
+ this.state = { tag: "ground" }
1674
+ this.consumePrefix(this.cursor)
1675
+ continue
1676
+ }
1677
+
1678
+ if (this.state.sawEsc) {
1679
+ if (byte === 0x5c) {
1680
+ const end = this.cursor + 1
1681
+ this.emitOpaqueResponse("apc", bytes.subarray(this.unitStart, end))
1682
+ this.state = { tag: "ground" }
1683
+ this.consumePrefix(end)
1684
+ continue
1685
+ }
1686
+
1687
+ this.state = { tag: "apc", sawEsc: false }
1688
+ continue
1689
+ }
1690
+
1691
+ if (byte === ESC) {
1692
+ this.cursor += 1
1693
+ this.state = { tag: "apc", sawEsc: true }
1694
+ continue
1695
+ }
1696
+
1697
+ this.cursor += 1
1698
+ continue
1699
+ }
1700
+
1701
+ // Delayed SGR mouse continuation after `esc_recovery` has consumed the
1702
+ // leading `[`. Reconstruct the already-flushed ESC for valid mouse
1703
+ // reports so wheel/click input still works; keep malformed or partial
1704
+ // bytes opaque so they never leak into text input.
1705
+ case "esc_less_mouse": {
1706
+ if (this.cursor >= bytes.length) {
1707
+ if (!this.forceFlush) {
1708
+ this.markPending()
1709
+ return
1710
+ }
1711
+
1712
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1713
+ this.state = { tag: "ground" }
1714
+ this.consumePrefix(this.cursor)
1715
+ continue
1716
+ }
1717
+
1718
+ if ((byte >= 0x30 && byte <= 0x39) || byte === 0x3b) {
1719
+ this.cursor += 1
1720
+ continue
1721
+ }
1722
+
1723
+ if (byte === 0x4d || byte === 0x6d) {
1724
+ const end = this.cursor + 1
1725
+ const rawBytes = bytes.subarray(this.unitStart, end)
1726
+ const prefixed = withEscPrefix(rawBytes)
1727
+ if (isMouseSgrSequence(prefixed)) {
1728
+ this.emitMouse(prefixed, "sgr")
1729
+ } else {
1730
+ this.emitOpaqueResponse("unknown", rawBytes)
1731
+ }
1732
+ this.state = { tag: "ground" }
1733
+ this.consumePrefix(end)
1734
+ continue
1735
+ }
1736
+
1737
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, this.cursor))
1738
+ this.state = { tag: "ground" }
1739
+ this.consumePrefix(this.cursor)
1740
+ continue
1741
+ }
1742
+
1743
+ // Delayed X10 mouse continuation after `esc_recovery` has consumed the
1744
+ // leading `[`. Reconstruct the already-flushed ESC for valid mouse
1745
+ // reports so wheel/click input still works; keep malformed or partial
1746
+ // bytes opaque so they never leak into text input.
1747
+ case "esc_less_x10_mouse": {
1748
+ const end = this.unitStart + 5
1749
+
1750
+ if (bytes.length < end) {
1751
+ if (!this.forceFlush) {
1752
+ this.markPending()
1753
+ return
1754
+ }
1755
+
1756
+ this.emitOpaqueResponse("unknown", bytes.subarray(this.unitStart, bytes.length))
1757
+ this.state = { tag: "ground" }
1758
+ this.consumePrefix(bytes.length)
1759
+ continue
1760
+ }
1761
+
1762
+ const rawBytes = bytes.subarray(this.unitStart, end)
1763
+ this.emitMouse(withEscPrefix(rawBytes), "x10")
1764
+ this.state = { tag: "ground" }
1765
+ this.consumePrefix(end)
1766
+ continue
1767
+ }
1768
+ }
1769
+ }
1770
+ }
1771
+
1772
+ // Tries to parse the raw string as a key via parseKeypress(). If it
1773
+ // recognizes the sequence (printable char, arrow, function key, etc.),
1774
+ // emits a key event. Otherwise emits a response event — this is how
1775
+ // capability responses, focus sequences, and other non-key CSI traffic
1776
+ // avoids becoming text.
1777
+ private emitKeyOrResponse(protocol: StdinResponseProtocol, raw: string): void {
1778
+ const parsed = parseKeypress(raw, { useKittyKeyboard: this.useKittyKeyboard })
1779
+ if (parsed) {
1780
+ this.events.push({
1781
+ type: "key",
1782
+ raw: parsed.raw,
1783
+ key: parsed,
1784
+ })
1785
+ return
1786
+ }
1787
+
1788
+ this.events.push({
1789
+ type: "response",
1790
+ protocol,
1791
+ sequence: raw,
1792
+ })
1793
+ }
1794
+
1795
+ private emitMouse(rawBytes: Uint8Array, encoding: "sgr" | "x10"): void {
1796
+ const event = this.mouseParser.parseMouseEvent(rawBytes)
1797
+ if (!event) {
1798
+ this.emitOpaqueResponse("unknown", rawBytes)
1799
+ return
1800
+ }
1801
+
1802
+ this.events.push({
1803
+ type: "mouse",
1804
+ raw: decodeLatin1(rawBytes),
1805
+ encoding,
1806
+ event,
1807
+ })
1808
+ }
1809
+
1810
+ // Handles single bytes in the 0x80–0xFF range that aren't valid UTF-8
1811
+ // leads. Passes them through parseKeypress() which maps them to the
1812
+ // existing meta-key behavior (e.g. Alt+letter in terminals that send
1813
+ // high bytes instead of ESC-prefixed sequences).
1814
+ private emitLegacyHighByte(byte: number): void {
1815
+ const parsed = parseKeypress(Buffer.from([byte]), { useKittyKeyboard: this.useKittyKeyboard })
1816
+ if (parsed) {
1817
+ this.events.push({
1818
+ type: "key",
1819
+ raw: parsed.raw,
1820
+ key: parsed,
1821
+ })
1822
+ return
1823
+ }
1824
+
1825
+ this.events.push({
1826
+ type: "response",
1827
+ protocol: "unknown",
1828
+ sequence: String.fromCharCode(byte),
1829
+ })
1830
+ }
1831
+
1832
+ private emitOpaqueResponse(protocol: StdinResponseProtocol, rawBytes: Uint8Array): void {
1833
+ this.events.push({
1834
+ type: "response",
1835
+ protocol,
1836
+ sequence: decodeLatin1(rawBytes),
1837
+ })
1838
+ }
1839
+
1840
+ // Advances past a completed protocol unit. Resets cursor, unitStart,
1841
+ // and timeout state so the next scan iteration starts clean.
1842
+ private consumePrefix(endExclusive: number): void {
1843
+ this.pending.consume(endExclusive)
1844
+ this.cursor = 0
1845
+ this.unitStart = 0
1846
+ this.pendingSinceMs = null
1847
+ this.forceFlush = false
1848
+ }
1849
+
1850
+ // Removes all bytes from the pending queue and returns them. Used when
1851
+ // entering paste mode — leftover bytes after the paste start marker
1852
+ // need to flow through consumePasteBytes() instead.
1853
+ private takePendingBytes(): Uint8Array {
1854
+ const buffered = this.pending.take()
1855
+ this.cursor = 0
1856
+ this.unitStart = 0
1857
+ this.pendingSinceMs = null
1858
+ this.forceFlush = false
1859
+ return buffered
1860
+ }
1861
+
1862
+ // Emits all pending bytes as one opaque response and clears the buffer.
1863
+ // This keeps the parser buffer bounded at maxPendingBytes without
1864
+ // dropping data or splitting it into per-character events.
1865
+ private flushPendingOverflow(): void {
1866
+ if (this.pending.length === 0) {
1867
+ return
1868
+ }
1869
+
1870
+ this.emitOpaqueResponse("unknown", this.pending.view())
1871
+ this.pending.clear()
1872
+ this.cursor = 0
1873
+ this.unitStart = 0
1874
+ this.pendingSinceMs = null
1875
+ this.forceFlush = false
1876
+ this.state = { tag: "ground" }
1877
+ }
1878
+
1879
+ // Records when incomplete data first appeared so flushTimeout() can
1880
+ // decide whether enough time has elapsed to force-flush it.
1881
+ private markPending(): void {
1882
+ this.pendingSinceMs = this.clock.now()
1883
+ }
1884
+
1885
+ // Processes bytes during an active bracketed paste. Searches for the end
1886
+ // marker (ESC[201~) using a sliding tail window so the marker can split
1887
+ // across chunk boundaries. Bytes that can't be part of the end marker are
1888
+ // appended to the paste collector without decoding.
1889
+ //
1890
+ // Returns any bytes that follow the end marker — those go back through
1891
+ // normal parsing in the push() loop.
1892
+ private consumePasteBytes(chunk: Uint8Array): Uint8Array {
1893
+ const paste = this.paste!
1894
+ const combined = concatBytes(paste.tail, chunk)
1895
+ const endIndex = indexOfBytes(combined, BRACKETED_PASTE_END)
1896
+
1897
+ if (endIndex !== -1) {
1898
+ this.pushPasteBytes(combined.subarray(0, endIndex))
1899
+
1900
+ this.events.push({
1901
+ type: "paste",
1902
+ bytes: joinPasteBytes(paste.parts, paste.totalLength),
1903
+ })
1904
+
1905
+ this.paste = null
1906
+ return combined.subarray(endIndex + BRACKETED_PASTE_END.length)
1907
+ }
1908
+
1909
+ // Keep enough trailing bytes to detect an end marker split across chunks.
1910
+ // Everything before that point is safe to retain immediately.
1911
+ const keep = Math.min(BRACKETED_PASTE_END.length - 1, combined.length)
1912
+ const stableLength = combined.length - keep
1913
+ if (stableLength > 0) {
1914
+ this.pushPasteBytes(combined.subarray(0, stableLength))
1915
+ }
1916
+
1917
+ paste.tail = Uint8Array.from(combined.subarray(stableLength))
1918
+ return EMPTY_BYTES
1919
+ }
1920
+
1921
+ private pushPasteBytes(bytes: Uint8Array): void {
1922
+ if (bytes.length === 0) {
1923
+ return
1924
+ }
1925
+
1926
+ // Copy here because subarray() inputs may alias the caller's chunk or the
1927
+ // parser's pending buffer across pushes. The emitted paste event must keep
1928
+ // the original bytes even if those backing buffers are later reused.
1929
+ this.paste!.parts.push(Uint8Array.from(bytes))
1930
+ this.paste!.totalLength += bytes.length
1931
+ }
1932
+
1933
+ private reconcileDeferredStateWithProtocolContext(): void {
1934
+ switch (this.state.tag) {
1935
+ case "csi_parametric_deferred":
1936
+ if (!canDeferParametricCsi(this.state, this.protocolContext)) {
1937
+ this.emitOpaqueResponse("unknown", this.pending.view().subarray(this.unitStart, this.cursor))
1938
+ this.state = { tag: "ground" }
1939
+ this.consumePrefix(this.cursor)
1940
+ }
1941
+ return
1942
+
1943
+ case "csi_private_reply_deferred":
1944
+ if (!canDeferPrivateReplyCsi(this.protocolContext)) {
1945
+ this.emitOpaqueResponse("unknown", this.pending.view().subarray(this.unitStart, this.cursor))
1946
+ this.state = { tag: "ground" }
1947
+ this.consumePrefix(this.cursor)
1948
+ }
1949
+ return
1950
+ }
1951
+ }
1952
+
1953
+ // Arms or disarms the timeout after every push(). If there's an incomplete
1954
+ // unit in the buffer, starts a timer. When the timer fires, it sets
1955
+ // forceFlush so the next read() converts the incomplete unit into one
1956
+ // atomic event (e.g. a lone ESC becoming an Escape key).
1957
+ private reconcileTimeoutState(): void {
1958
+ if (!this.armTimeouts) {
1959
+ return
1960
+ }
1961
+
1962
+ if (this.paste || this.pendingSinceMs === null || this.pending.length === 0) {
1963
+ this.clearTimeout()
1964
+ return
1965
+ }
1966
+
1967
+ this.clearTimeout()
1968
+ this.timeoutId = this.clock.setTimeout(() => {
1969
+ this.timeoutId = null
1970
+ if (this.destroyed) {
1971
+ return
1972
+ }
1973
+
1974
+ try {
1975
+ this.tryForceFlush()
1976
+ this.onTimeoutFlush?.()
1977
+ } catch (error) {
1978
+ console.error("stdin parser timeout flush failed", error)
1979
+ }
1980
+ }, this.timeoutMs)
1981
+ }
1982
+
1983
+ private clearTimeout(): void {
1984
+ if (!this.timeoutId) {
1985
+ return
1986
+ }
1987
+
1988
+ this.clock.clearTimeout(this.timeoutId)
1989
+ this.timeoutId = null
1990
+ }
1991
+
1992
+ // Clears all parser state: pending bytes, queued events, timeout tracking,
1993
+ // and any active paste collector. Called by both reset() (suspend/resume)
1994
+ // and destroy() to ensure no stale state survives.
1995
+ private resetState(): void {
1996
+ this.pending.reset(INITIAL_PENDING_CAPACITY)
1997
+ this.events.length = 0
1998
+ this.pendingSinceMs = null
1999
+ this.forceFlush = false
2000
+ this.justFlushedEsc = false
2001
+ this.state = { tag: "ground" }
2002
+ this.cursor = 0
2003
+ this.unitStart = 0
2004
+ this.paste = null
2005
+ this.mouseParser.reset()
2006
+ }
2007
+ }