@humain/humain-code 0.4.12 → 0.4.13

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 (539) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/bun/sandbox-env-setup.js +1 -1
  3. package/dist/bun/sandbox-env-setup.js.map +1 -1
  4. package/dist/bundle/agent-monitor.js +1 -1
  5. package/dist/bundle/chunks/anthropic-messages-YSAHA7QM.js +67 -0
  6. package/dist/bundle/chunks/azure-openai-responses-Z5XYDPHS.js +15 -0
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +393 -314
  8. package/dist/bundle/chunks/{chunk-EDKZRYWJ.js → chunk-2TTB6GIB.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-HSDTSUZE.js → chunk-36Q5UVQL.js} +47 -89
  10. package/dist/bundle/chunks/chunk-4DXXZHY2.js +540 -0
  11. package/dist/bundle/chunks/{chunk-BKJU56SM.js → chunk-A7QKOI62.js} +142 -126
  12. package/dist/bundle/chunks/{chunk-UW4GMZL3.js → chunk-AIXI6RIE.js} +264 -248
  13. package/dist/bundle/chunks/{chunk-V5ZF7Q7L.js → chunk-BVHXWQLD.js} +52 -47
  14. package/dist/bundle/chunks/{chunk-I2ZWZAIV.js → chunk-COF5P635.js} +222 -148
  15. package/dist/bundle/chunks/{chunk-SCIGZFN5.js → chunk-DNGJMRJW.js} +11 -11
  16. package/dist/bundle/chunks/{chunk-XGO43DKL.js → chunk-DUSJT2W4.js} +21 -25
  17. package/dist/bundle/chunks/chunk-EYIYBQAR.js +7 -0
  18. package/dist/bundle/chunks/chunk-FRUFMISJ.js +505 -0
  19. package/dist/bundle/chunks/{chunk-R5VIAWGA.js → chunk-H2FY3PEV.js} +9 -8
  20. package/dist/bundle/chunks/{chunk-KGI4EX6R.js → chunk-JNHXXVLA.js} +126 -125
  21. package/dist/bundle/chunks/{chunk-45ZBHMQG.js → chunk-JQCWRL5K.js} +4 -4
  22. package/dist/bundle/chunks/{chunk-AS2Y2MO6.js → chunk-KK3KUUMM.js} +643 -624
  23. package/dist/bundle/chunks/{chunk-6KAMTNN3.js → chunk-L3J4P5JR.js} +1 -1
  24. package/dist/bundle/chunks/chunk-L6Z6JKKC.js +3 -0
  25. package/dist/bundle/chunks/{chunk-DZ5C66IU.js → chunk-LUL775V7.js} +33 -33
  26. package/dist/bundle/chunks/{chunk-BRXQUQSC.js → chunk-MF2NEHP4.js} +778 -775
  27. package/dist/bundle/chunks/chunk-MG5PX4KU.js +31 -0
  28. package/dist/bundle/chunks/{chunk-LCOHFEZZ.js → chunk-NNKA2PAP.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-HMWAH7ZY.js → chunk-OX2IBCCA.js} +53 -49
  30. package/dist/bundle/chunks/{chunk-WBJN6PEI.js → chunk-QYCOHSI7.js} +1 -1
  31. package/dist/bundle/chunks/{chunk-NLTW6A7G.js → chunk-TC7EANW4.js} +3730 -3353
  32. package/dist/bundle/chunks/{chunk-77EWF2NW.js → chunk-TJG52LZB.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-5XD3DHYL.js → chunk-UDVC7A5S.js} +1 -1
  34. package/dist/bundle/chunks/chunk-UGXYG7HN.js +22 -0
  35. package/dist/bundle/chunks/{chunk-VYIIPF57.js → chunk-UHLW4KJ7.js} +419 -413
  36. package/dist/bundle/chunks/{chunk-FF26YENK.js → chunk-W2QRCQBX.js} +4 -3
  37. package/dist/bundle/chunks/chunk-XQRYOCHA.js +26 -0
  38. package/dist/bundle/chunks/{chunk-7Z5MWPYE.js → chunk-Y3RFGBG2.js} +1 -1
  39. package/dist/bundle/chunks/chunk-YJ3NQWES.js +9 -0
  40. package/dist/bundle/chunks/{chunk-YJBE3IGR.js → chunk-YRCLNWFV.js} +20 -20
  41. package/dist/bundle/chunks/chunk-YZMQXAJM.js +8 -0
  42. package/dist/bundle/chunks/{chunk-BHM75BJJ.js → chunk-Z74ZYQPX.js} +207 -79
  43. package/dist/bundle/chunks/{cli-5ACW3WND.js → cli-SRI4UOSL.js} +6 -6
  44. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FZ3UQCZ7.js → cloudflare-workers-ai-system-one-JGN7NZCV.js} +1 -1
  45. package/dist/bundle/chunks/codemode-worker.js +27 -14
  46. package/dist/bundle/chunks/{compat-KXWWOFHQ.js → compat-PCHMBE76.js} +6 -6
  47. package/dist/bundle/chunks/dist-MNSGVI4C.js +7 -0
  48. package/dist/bundle/chunks/{dist-6SWVHFCS.js → dist-UWE5M6HK.js} +211 -8
  49. package/dist/bundle/chunks/{dist-cjs-RL2OCAP2.js → dist-cjs-4BMVQ74V.js} +1 -1
  50. package/dist/bundle/chunks/{easter-egg-3d-3L3IKAT6.js → easter-egg-3d-ZJ2JUFOA.js} +1 -1
  51. package/dist/bundle/chunks/es-YEFEOGR3.js +1905 -0
  52. package/dist/bundle/chunks/{esm-763X2IA7.js → esm-NCUV2DF7.js} +1 -1
  53. package/dist/bundle/chunks/{event-streams-R5OECII4.js → event-streams-NXFTZDSF.js} +1 -1
  54. package/dist/bundle/chunks/execute-LRTXH4YJ.js +553 -0
  55. package/dist/bundle/chunks/{extract-DLZ425VI.js → extract-OZW5JHG6.js} +140 -120
  56. package/dist/bundle/chunks/{google-generative-ai-JD2FVOIX.js → google-generative-ai-YXXFSTX7.js} +2 -2
  57. package/dist/bundle/chunks/{google-vertex-PFBMDCBW.js → google-vertex-3IVWLYJ5.js} +2 -2
  58. package/dist/bundle/chunks/host-2RMBOGA7.js +2 -0
  59. package/dist/bundle/chunks/{mistral-conversations-D74NZ65O.js → mistral-conversations-Y7GWO3QB.js} +14 -13
  60. package/dist/bundle/chunks/{node-W47VUEGE.js → node-ELWNZC34.js} +328 -337
  61. package/dist/bundle/chunks/{node-4GGYDW5Q.js → node-SPBTZUUS.js} +26 -25
  62. package/dist/bundle/chunks/{openai-codex-responses-JAAA7MSS.js → openai-codex-responses-NSXWHIDT.js} +3 -4
  63. package/dist/bundle/chunks/{openai-completions-PGPMGQPU.js → openai-completions-WGBQHTYA.js} +9 -8
  64. package/dist/bundle/chunks/{openai-decisions-QQ4MEABI.js → openai-decisions-QWEISDVO.js} +1 -1
  65. package/dist/bundle/chunks/{openai-responses-FG2R2M4L.js → openai-responses-OKGCSIEY.js} +6 -6
  66. package/dist/bundle/chunks/{openrouter-images-NTBP3UUE.js → openrouter-images-BMVMAROU.js} +1 -1
  67. package/dist/bundle/chunks/{pi-messages-JD4O7KIP.js → pi-messages-XNEG23NU.js} +1 -1
  68. package/dist/bundle/chunks/runtime-VGSK3QCM.js +2 -0
  69. package/dist/bundle/chunks/{typesafe-system-one-TTC7YCO3.js → typesafe-system-one-62YHYXZV.js} +1 -1
  70. package/dist/bundle/chunks/{undici-EEOUTE5F.js → undici-7EW63V4X.js} +1 -1
  71. package/dist/bundle/chunks/virtual-modules-JSGQ72M6.js +5 -0
  72. package/dist/bundle/cli-runtime.js +3 -3
  73. package/dist/bundle/flow/package.json +5 -6
  74. package/dist/bundle/index.js +6 -6
  75. package/dist/bundle/rpc-entry.js +2 -2
  76. package/dist/coordination/adapter/delivery.d.ts.map +1 -1
  77. package/dist/coordination/adapter/delivery.js +1 -0
  78. package/dist/coordination/adapter/delivery.js.map +1 -1
  79. package/dist/coordination/adapter/index.d.ts.map +1 -1
  80. package/dist/coordination/adapter/index.js +3 -1
  81. package/dist/coordination/adapter/index.js.map +1 -1
  82. package/dist/coordination/adapter/receipts.d.ts +2 -1
  83. package/dist/coordination/adapter/receipts.d.ts.map +1 -1
  84. package/dist/coordination/adapter/receipts.js +7 -4
  85. package/dist/coordination/adapter/receipts.js.map +1 -1
  86. package/dist/coordination/adapter/supervisor.d.ts.map +1 -1
  87. package/dist/coordination/adapter/supervisor.js +8 -0
  88. package/dist/coordination/adapter/supervisor.js.map +1 -1
  89. package/dist/coordination/broker/broker.d.ts +11 -0
  90. package/dist/coordination/broker/broker.d.ts.map +1 -1
  91. package/dist/coordination/broker/broker.js +195 -18
  92. package/dist/coordination/broker/broker.js.map +1 -1
  93. package/dist/coordination/client/client.d.ts +5 -0
  94. package/dist/coordination/client/client.d.ts.map +1 -1
  95. package/dist/coordination/client/client.js +23 -9
  96. package/dist/coordination/client/client.js.map +1 -1
  97. package/dist/coordination/transport/protocol.d.ts.map +1 -1
  98. package/dist/coordination/transport/protocol.js +8 -1
  99. package/dist/coordination/transport/protocol.js.map +1 -1
  100. package/dist/coordination/transport/types.d.ts +6 -0
  101. package/dist/coordination/transport/types.d.ts.map +1 -1
  102. package/dist/coordination/transport/types.js +2 -1
  103. package/dist/coordination/transport/types.js.map +1 -1
  104. package/dist/core/agent-session.d.ts +44 -2
  105. package/dist/core/agent-session.d.ts.map +1 -1
  106. package/dist/core/agent-session.js +305 -124
  107. package/dist/core/agent-session.js.map +1 -1
  108. package/dist/core/auth-storage.d.ts.map +1 -1
  109. package/dist/core/auth-storage.js +20 -13
  110. package/dist/core/auth-storage.js.map +1 -1
  111. package/dist/core/auto-effort.d.ts +16 -0
  112. package/dist/core/auto-effort.d.ts.map +1 -0
  113. package/dist/core/auto-effort.js +69 -0
  114. package/dist/core/auto-effort.js.map +1 -0
  115. package/dist/core/auto-session-namer.d.ts.map +1 -1
  116. package/dist/core/auto-session-namer.js +2 -12
  117. package/dist/core/auto-session-namer.js.map +1 -1
  118. package/dist/core/bug-report.d.ts +11 -1
  119. package/dist/core/bug-report.d.ts.map +1 -1
  120. package/dist/core/bug-report.js +2 -2
  121. package/dist/core/bug-report.js.map +1 -1
  122. package/dist/core/compaction/branch-summarization.d.ts +3 -2
  123. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  124. package/dist/core/compaction/branch-summarization.js +1 -1
  125. package/dist/core/compaction/branch-summarization.js.map +1 -1
  126. package/dist/core/compaction/compaction.d.ts +13 -4
  127. package/dist/core/compaction/compaction.d.ts.map +1 -1
  128. package/dist/core/compaction/compaction.js +94 -5
  129. package/dist/core/compaction/compaction.js.map +1 -1
  130. package/dist/core/compaction/utils.d.ts +6 -0
  131. package/dist/core/compaction/utils.d.ts.map +1 -1
  132. package/dist/core/compaction/utils.js +7 -8
  133. package/dist/core/compaction/utils.js.map +1 -1
  134. package/dist/core/extensions/index.d.ts +1 -1
  135. package/dist/core/extensions/index.d.ts.map +1 -1
  136. package/dist/core/extensions/index.js.map +1 -1
  137. package/dist/core/extensions/runner.d.ts +4 -2
  138. package/dist/core/extensions/runner.d.ts.map +1 -1
  139. package/dist/core/extensions/runner.js +6 -3
  140. package/dist/core/extensions/runner.js.map +1 -1
  141. package/dist/core/extensions/types.d.ts +33 -7
  142. package/dist/core/extensions/types.d.ts.map +1 -1
  143. package/dist/core/extensions/types.js.map +1 -1
  144. package/dist/core/key-id-schema.d.ts +6 -0
  145. package/dist/core/key-id-schema.d.ts.map +1 -0
  146. package/dist/core/key-id-schema.js +16 -0
  147. package/dist/core/key-id-schema.js.map +1 -0
  148. package/dist/core/keybindings-schema.d.ts +4 -0
  149. package/dist/core/keybindings-schema.d.ts.map +1 -0
  150. package/dist/core/keybindings-schema.js +16 -0
  151. package/dist/core/keybindings-schema.js.map +1 -0
  152. package/dist/core/keybindings.d.ts +198 -63
  153. package/dist/core/keybindings.d.ts.map +1 -1
  154. package/dist/core/keybindings.js +26 -23
  155. package/dist/core/keybindings.js.map +1 -1
  156. package/dist/core/model-config.d.ts +695 -74
  157. package/dist/core/model-config.d.ts.map +1 -1
  158. package/dist/core/model-config.js +16 -166
  159. package/dist/core/model-config.js.map +1 -1
  160. package/dist/core/model-runtime.d.ts.map +1 -1
  161. package/dist/core/model-runtime.js +39 -4
  162. package/dist/core/model-runtime.js.map +1 -1
  163. package/dist/core/package-manager.d.ts.map +1 -1
  164. package/dist/core/package-manager.js +3 -3
  165. package/dist/core/package-manager.js.map +1 -1
  166. package/dist/core/project-trust.d.ts.map +1 -1
  167. package/dist/core/project-trust.js +2 -1
  168. package/dist/core/project-trust.js.map +1 -1
  169. package/dist/core/remote-catalog-provider.d.ts +13 -1
  170. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  171. package/dist/core/remote-catalog-provider.js +110 -27
  172. package/dist/core/remote-catalog-provider.js.map +1 -1
  173. package/dist/core/resource-loader.d.ts.map +1 -1
  174. package/dist/core/resource-loader.js +5 -1
  175. package/dist/core/resource-loader.js.map +1 -1
  176. package/dist/core/session-export.d.ts.map +1 -1
  177. package/dist/core/session-export.js +2 -2
  178. package/dist/core/session-export.js.map +1 -1
  179. package/dist/core/session-manager.d.ts +36 -5
  180. package/dist/core/session-manager.d.ts.map +1 -1
  181. package/dist/core/session-manager.js +164 -40
  182. package/dist/core/session-manager.js.map +1 -1
  183. package/dist/core/settings-defaults.d.ts +65 -0
  184. package/dist/core/settings-defaults.d.ts.map +1 -0
  185. package/dist/core/settings-defaults.js +66 -0
  186. package/dist/core/settings-defaults.js.map +1 -0
  187. package/dist/core/settings-manager.d.ts +10 -175
  188. package/dist/core/settings-manager.d.ts.map +1 -1
  189. package/dist/core/settings-manager.js +64 -44
  190. package/dist/core/settings-manager.js.map +1 -1
  191. package/dist/core/settings-schema.d.ts +257 -0
  192. package/dist/core/settings-schema.d.ts.map +1 -0
  193. package/dist/core/settings-schema.js +311 -0
  194. package/dist/core/settings-schema.js.map +1 -0
  195. package/dist/core/tools/edit-diff.d.ts +4 -1
  196. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  197. package/dist/core/tools/edit-diff.js +480 -29
  198. package/dist/core/tools/edit-diff.js.map +1 -1
  199. package/dist/core/tools/render-utils.d.ts +18 -0
  200. package/dist/core/tools/render-utils.d.ts.map +1 -1
  201. package/dist/core/tools/render-utils.js +46 -0
  202. package/dist/core/tools/render-utils.js.map +1 -1
  203. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  204. package/dist/core/tools/renderers/bash.js +17 -46
  205. package/dist/core/tools/renderers/bash.js.map +1 -1
  206. package/dist/core/tools/renderers/edit.d.ts +19 -1
  207. package/dist/core/tools/renderers/edit.d.ts.map +1 -1
  208. package/dist/core/tools/renderers/edit.js +38 -7
  209. package/dist/core/tools/renderers/edit.js.map +1 -1
  210. package/dist/core/tools/renderers/find.d.ts.map +1 -1
  211. package/dist/core/tools/renderers/find.js +3 -0
  212. package/dist/core/tools/renderers/find.js.map +1 -1
  213. package/dist/core/tools/renderers/grep.d.ts.map +1 -1
  214. package/dist/core/tools/renderers/grep.js +3 -0
  215. package/dist/core/tools/renderers/grep.js.map +1 -1
  216. package/dist/core/tools/renderers/highlighting.d.ts +13 -0
  217. package/dist/core/tools/renderers/highlighting.d.ts.map +1 -0
  218. package/dist/core/tools/renderers/highlighting.js +42 -0
  219. package/dist/core/tools/renderers/highlighting.js.map +1 -0
  220. package/dist/core/tools/renderers/ls.d.ts.map +1 -1
  221. package/dist/core/tools/renderers/ls.js +3 -0
  222. package/dist/core/tools/renderers/ls.js.map +1 -1
  223. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  224. package/dist/core/tools/renderers/read.js +3 -0
  225. package/dist/core/tools/renderers/read.js.map +1 -1
  226. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  227. package/dist/core/tools/renderers/write.js +3 -1
  228. package/dist/core/tools/renderers/write.js.map +1 -1
  229. package/dist/core/tools/subagent.d.ts +4 -0
  230. package/dist/core/tools/subagent.d.ts.map +1 -1
  231. package/dist/core/tools/subagent.js +85 -8
  232. package/dist/core/tools/subagent.js.map +1 -1
  233. package/dist/core/tools/truncate.d.ts.map +1 -1
  234. package/dist/core/tools/truncate.js +92 -44
  235. package/dist/core/tools/truncate.js.map +1 -1
  236. package/dist/core/usage-totals.d.ts +8 -1
  237. package/dist/core/usage-totals.d.ts.map +1 -1
  238. package/dist/core/usage-totals.js +106 -10
  239. package/dist/core/usage-totals.js.map +1 -1
  240. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  241. package/dist/extensions/codemode/execute.js +64 -45
  242. package/dist/extensions/codemode/execute.js.map +1 -1
  243. package/dist/extensions/codemode/index.d.ts.map +1 -1
  244. package/dist/extensions/codemode/index.js +2 -1
  245. package/dist/extensions/codemode/index.js.map +1 -1
  246. package/dist/extensions/codemode/renderer.d.ts +2 -2
  247. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  248. package/dist/extensions/codemode/renderer.js +9 -3
  249. package/dist/extensions/codemode/renderer.js.map +1 -1
  250. package/dist/extensions/codemode/tool.d.ts +6 -12
  251. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  252. package/dist/extensions/codemode/tool.js +44 -32
  253. package/dist/extensions/codemode/tool.js.map +1 -1
  254. package/dist/extensions/mcp/cli.js +5 -8
  255. package/dist/extensions/mcp/cli.js.map +1 -1
  256. package/dist/extensions/mcp/index.d.ts.map +1 -1
  257. package/dist/extensions/mcp/index.js +26 -23
  258. package/dist/extensions/mcp/index.js.map +1 -1
  259. package/dist/extensions/mcp/resources.d.ts +0 -6
  260. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  261. package/dist/extensions/mcp/resources.js +1 -1
  262. package/dist/extensions/mcp/resources.js.map +1 -1
  263. package/dist/extensions/mcp/runtime.d.ts +3 -6
  264. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  265. package/dist/extensions/mcp/runtime.js +4 -39
  266. package/dist/extensions/mcp/runtime.js.map +1 -1
  267. package/dist/extensions/mcp/tools.d.ts +2 -3
  268. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  269. package/dist/extensions/mcp/tools.js +62 -6
  270. package/dist/extensions/mcp/tools.js.map +1 -1
  271. package/dist/extensions/tool-search/tool.d.ts +0 -2
  272. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  273. package/dist/extensions/tool-search/tool.js +2 -4
  274. package/dist/extensions/tool-search/tool.js.map +1 -1
  275. package/dist/humain/adhd/index.d.ts +3 -2
  276. package/dist/humain/adhd/index.d.ts.map +1 -1
  277. package/dist/humain/adhd/index.js +22 -10
  278. package/dist/humain/adhd/index.js.map +1 -1
  279. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +306 -20
  280. package/dist/humain/caveman/index.d.ts +4 -2
  281. package/dist/humain/caveman/index.d.ts.map +1 -1
  282. package/dist/humain/caveman/index.js +51 -16
  283. package/dist/humain/caveman/index.js.map +1 -1
  284. package/dist/humain/ponytail/index.d.ts +2 -0
  285. package/dist/humain/ponytail/index.d.ts.map +1 -1
  286. package/dist/humain/ponytail/index.js +2 -0
  287. package/dist/humain/ponytail/index.js.map +1 -1
  288. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
  289. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +39 -9
  290. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
  291. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +1 -1
  292. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
  293. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts +4 -0
  294. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
  295. package/dist/humain/ponytail/vendor/pi-extension/index.js +8 -0
  296. package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
  297. package/dist/humain/web-access/vendor/baizhi.js.map +1 -1
  298. package/dist/humain/web-access/vendor/brave.d.ts.map +1 -1
  299. package/dist/humain/web-access/vendor/brave.js +19 -2
  300. package/dist/humain/web-access/vendor/brave.js.map +1 -1
  301. package/dist/humain/web-access/vendor/ceramic.d.ts +4 -0
  302. package/dist/humain/web-access/vendor/ceramic.d.ts.map +1 -0
  303. package/dist/humain/web-access/vendor/ceramic.js +212 -0
  304. package/dist/humain/web-access/vendor/ceramic.js.map +1 -0
  305. package/dist/humain/web-access/vendor/content-find.d.ts.map +1 -1
  306. package/dist/humain/web-access/vendor/content-find.js +2 -1
  307. package/dist/humain/web-access/vendor/content-find.js.map +1 -1
  308. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  309. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  310. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  311. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  312. package/dist/humain/web-access/vendor/curator-server.js +2 -0
  313. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  314. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
  315. package/dist/humain/web-access/vendor/duckduckgo.js +5 -1
  316. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
  317. package/dist/humain/web-access/vendor/endpoint-pdf-extract.d.ts +23 -0
  318. package/dist/humain/web-access/vendor/endpoint-pdf-extract.d.ts.map +1 -0
  319. package/dist/humain/web-access/vendor/endpoint-pdf-extract.js +193 -0
  320. package/dist/humain/web-access/vendor/endpoint-pdf-extract.js.map +1 -0
  321. package/dist/humain/web-access/vendor/extract.d.ts +5 -1
  322. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  323. package/dist/humain/web-access/vendor/extract.js +49 -12
  324. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  325. package/dist/humain/web-access/vendor/fetch-params.d.ts +2 -0
  326. package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -1
  327. package/dist/humain/web-access/vendor/fetch-params.js +9 -0
  328. package/dist/humain/web-access/vendor/fetch-params.js.map +1 -1
  329. package/dist/humain/web-access/vendor/gemini-api.d.ts +5 -0
  330. package/dist/humain/web-access/vendor/gemini-api.d.ts.map +1 -1
  331. package/dist/humain/web-access/vendor/gemini-api.js +16 -0
  332. package/dist/humain/web-access/vendor/gemini-api.js.map +1 -1
  333. package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
  334. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  335. package/dist/humain/web-access/vendor/gemini-search.js +48 -172
  336. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  337. package/dist/humain/web-access/vendor/github-extract.d.ts +7 -0
  338. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
  339. package/dist/humain/web-access/vendor/github-extract.js +31 -2
  340. package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
  341. package/dist/humain/web-access/vendor/github-issue-pr.d.ts +2 -0
  342. package/dist/humain/web-access/vendor/github-issue-pr.d.ts.map +1 -1
  343. package/dist/humain/web-access/vendor/github-issue-pr.js +86 -74
  344. package/dist/humain/web-access/vendor/github-issue-pr.js.map +1 -1
  345. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  346. package/dist/humain/web-access/vendor/index.js +68 -27
  347. package/dist/humain/web-access/vendor/index.js.map +1 -1
  348. package/dist/humain/web-access/vendor/openai-search.js +3 -3
  349. package/dist/humain/web-access/vendor/openai-search.js.map +1 -1
  350. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  351. package/dist/humain/web-access/vendor/page-query.js +6 -9
  352. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  353. package/dist/humain/web-access/vendor/parallel-mcp.d.ts.map +1 -1
  354. package/dist/humain/web-access/vendor/parallel-mcp.js +2 -0
  355. package/dist/humain/web-access/vendor/parallel-mcp.js.map +1 -1
  356. package/dist/humain/web-access/vendor/pdf-extract.d.ts +1 -1
  357. package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -1
  358. package/dist/humain/web-access/vendor/pdf-extract.js +31 -1
  359. package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -1
  360. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  361. package/dist/humain/web-access/vendor/perplexity.js +21 -2
  362. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  363. package/dist/humain/web-access/vendor/query-rewrite.js +1 -1
  364. package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
  365. package/dist/humain/web-access/vendor/ssrf-protection.d.ts +4 -0
  366. package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -1
  367. package/dist/humain/web-access/vendor/ssrf-protection.js +19 -4
  368. package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -1
  369. package/dist/humain/web-access/vendor/storage.d.ts +14 -0
  370. package/dist/humain/web-access/vendor/storage.d.ts.map +1 -1
  371. package/dist/humain/web-access/vendor/storage.js +48 -0
  372. package/dist/humain/web-access/vendor/storage.js.map +1 -1
  373. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
  374. package/dist/humain/web-access/vendor/summary-review.js +18 -6
  375. package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
  376. package/dist/humain/web-access/vendor/tool-arguments.d.ts.map +1 -1
  377. package/dist/humain/web-access/vendor/tool-arguments.js +5 -2
  378. package/dist/humain/web-access/vendor/tool-arguments.js.map +1 -1
  379. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  380. package/dist/humain/web-access/vendor/utils.js +21 -6
  381. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  382. package/dist/humain/web-access/vendor/video-extract.js +6 -2
  383. package/dist/humain/web-access/vendor/video-extract.js.map +1 -1
  384. package/dist/humain/web-access/vendor/web-tool-core.d.ts +2 -1
  385. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  386. package/dist/humain/web-access/vendor/web-tool-core.js +56 -13
  387. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  388. package/dist/humain/web-access/vendor/zai.js.map +1 -1
  389. package/dist/index.d.ts +3 -3
  390. package/dist/index.d.ts.map +1 -1
  391. package/dist/index.js.map +1 -1
  392. package/dist/main.js +3 -3
  393. package/dist/main.js.map +1 -1
  394. package/dist/modes/interactive/components/assistant-message.d.ts +21 -1
  395. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  396. package/dist/modes/interactive/components/assistant-message.js +79 -10
  397. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  398. package/dist/modes/interactive/components/footer.d.ts +8 -3
  399. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  400. package/dist/modes/interactive/components/footer.js +156 -133
  401. package/dist/modes/interactive/components/footer.js.map +1 -1
  402. package/dist/modes/interactive/components/mermaid.js +1 -1
  403. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  404. package/dist/modes/interactive/components/settings-selector.d.ts +10 -1
  405. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  406. package/dist/modes/interactive/components/settings-selector.js +83 -7
  407. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  408. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  409. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  410. package/dist/modes/interactive/components/status-indicator.js +2 -2
  411. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  412. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  413. package/dist/modes/interactive/components/themed-text.js +3 -1
  414. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  415. package/dist/modes/interactive/components/tool-execution.d.ts +7 -1
  416. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  417. package/dist/modes/interactive/components/tool-execution.js +36 -19
  418. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  419. package/dist/modes/interactive/components/transcript-container.d.ts +12 -0
  420. package/dist/modes/interactive/components/transcript-container.d.ts.map +1 -0
  421. package/dist/modes/interactive/components/transcript-container.js +31 -0
  422. package/dist/modes/interactive/components/transcript-container.js.map +1 -0
  423. package/dist/modes/interactive/components/user-message.d.ts +6 -1
  424. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  425. package/dist/modes/interactive/components/user-message.js +20 -5
  426. package/dist/modes/interactive/components/user-message.js.map +1 -1
  427. package/dist/modes/interactive/components/visual-truncate.d.ts +20 -5
  428. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  429. package/dist/modes/interactive/components/visual-truncate.js +42 -3
  430. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  431. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  432. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  433. package/dist/modes/interactive/interactive-mode.js +125 -19
  434. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  435. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  436. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  437. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  438. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  439. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  440. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  441. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  442. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  443. package/dist/modes/interactive/theme/theme.d.ts +15 -16
  444. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  445. package/dist/modes/interactive/theme/theme.js +26 -29
  446. package/dist/modes/interactive/theme/theme.js.map +1 -1
  447. package/dist/modes/print-mode.d.ts.map +1 -1
  448. package/dist/modes/print-mode.js +4 -0
  449. package/dist/modes/print-mode.js.map +1 -1
  450. package/dist/utils/child-process.d.ts +0 -7
  451. package/dist/utils/child-process.d.ts.map +1 -1
  452. package/dist/utils/child-process.js +12 -3
  453. package/dist/utils/child-process.js.map +1 -1
  454. package/dist/utils/clipboard.d.ts.map +1 -1
  455. package/dist/utils/clipboard.js +6 -1
  456. package/dist/utils/clipboard.js.map +1 -1
  457. package/dist/utils/image-convert.d.ts +7 -0
  458. package/dist/utils/image-convert.d.ts.map +1 -1
  459. package/dist/utils/image-convert.js +35 -3
  460. package/dist/utils/image-convert.js.map +1 -1
  461. package/dist/utils/image-resize.d.ts.map +1 -1
  462. package/dist/utils/image-resize.js +2 -2
  463. package/dist/utils/image-resize.js.map +1 -1
  464. package/dist/utils/syntax-highlight.d.ts +7 -0
  465. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  466. package/dist/utils/syntax-highlight.js +54 -3
  467. package/dist/utils/syntax-highlight.js.map +1 -1
  468. package/dist/utils/windows-path.js +1 -1
  469. package/dist/utils/windows-path.js.map +1 -1
  470. package/dist/utils/zip.d.ts.map +1 -1
  471. package/dist/utils/zip.js +3 -1
  472. package/dist/utils/zip.js.map +1 -1
  473. package/docs/auto-session-namer.md +4 -0
  474. package/docs/cli-integration.md +1 -1
  475. package/docs/cli.md +1 -1
  476. package/docs/codemode.md +1 -1
  477. package/docs/compaction.md +9 -5
  478. package/docs/coordination.md +7 -0
  479. package/docs/environment-variables.md +1 -0
  480. package/docs/extensions.md +7 -4
  481. package/docs/keybindings.md +1 -0
  482. package/docs/mcp.md +1 -1
  483. package/docs/models.md +1 -0
  484. package/docs/providers.md +20 -0
  485. package/docs/session-format.md +16 -2
  486. package/docs/settings.md +16 -1
  487. package/docs/themes.md +4 -2
  488. package/docs/tui.md +1 -1
  489. package/docs/usage.md +6 -2
  490. package/examples/extensions/custom-provider-anthropic/package-lock.json +6 -6
  491. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  492. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  493. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  494. package/examples/extensions/gondolin/package-lock.json +20 -20
  495. package/examples/extensions/gondolin/package.json +1 -1
  496. package/examples/extensions/overlay-test.ts +2 -2
  497. package/examples/extensions/plan-mode/index.ts +6 -2
  498. package/examples/extensions/sandbox/package-lock.json +8 -8
  499. package/examples/extensions/sandbox/package.json +2 -2
  500. package/examples/extensions/with-deps/package-lock.json +2 -2
  501. package/examples/extensions/with-deps/package.json +1 -1
  502. package/examples/plugins/pi-example-plugin/package.json +2 -2
  503. package/examples/plugins/pi-example-plugin/src/contract.ts +1 -1
  504. package/examples/plugins/pi-example-plugin/src/session.ts +1 -1
  505. package/examples/plugins/pi-example-plugin/src/tui.ts +1 -1
  506. package/npm-shrinkwrap.json +174 -190
  507. package/package.json +24 -23
  508. package/schemas/keybindings.schema.json +397 -0
  509. package/schemas/models.schema.json +1157 -0
  510. package/schemas/settings.schema.json +875 -0
  511. package/schemas/theme.schema.json +365 -0
  512. package/src/coordination/UPSTREAM.md +36 -3
  513. package/src/coordination/upstream.json +3 -2
  514. package/src/humain/adhd/UPSTREAM.md +21 -3
  515. package/src/humain/adhd/upstream.json +1 -1
  516. package/src/humain/caveman/UPSTREAM.md +24 -3
  517. package/src/humain/ponytail/UPSTREAM.md +51 -4
  518. package/src/humain/ponytail/upstream.json +12 -12
  519. package/src/humain/ponytail/vendor/skills/ponytail/SKILL.md +1 -1
  520. package/src/humain/ponytail/vendor/skills/ponytail-audit/SKILL.md +1 -1
  521. package/src/humain/ponytail/vendor/skills/ponytail-debt/SKILL.md +13 -10
  522. package/src/humain/ponytail/vendor/skills/ponytail-help/SKILL.md +1 -1
  523. package/src/humain/ponytail/vendor/skills/ponytail-review/SKILL.md +1 -1
  524. package/src/humain/web-access/UPSTREAM.md +55 -1
  525. package/src/humain/web-access/upstream.json +4 -4
  526. package/dist/bundle/chunks/anthropic-messages-UNHXXOD4.js +0 -70
  527. package/dist/bundle/chunks/azure-openai-responses-4QRYJCC2.js +0 -14
  528. package/dist/bundle/chunks/chunk-GVVRXZHN.js +0 -17
  529. package/dist/bundle/chunks/chunk-QMUIATLD.js +0 -209
  530. package/dist/bundle/chunks/chunk-QSPDLT2R.js +0 -160
  531. package/dist/bundle/chunks/chunk-SZRZXVVZ.js +0 -125
  532. package/dist/bundle/chunks/chunk-XMHLSV3I.js +0 -48
  533. package/dist/bundle/chunks/chunk-YKZGL4MB.js +0 -86
  534. package/dist/bundle/chunks/dist-VNSMKBZ6.js +0 -7
  535. package/dist/bundle/chunks/es-N6YFJOD7.js +0 -1901
  536. package/dist/bundle/chunks/execute-4X6G65NZ.js +0 -536
  537. package/dist/bundle/chunks/host-4J7H7KDS.js +0 -2
  538. package/dist/bundle/chunks/runtime-SI76JZNE.js +0 -2
  539. package/dist/bundle/chunks/virtual-modules-GZY3Y4GX.js +0 -5
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{require_core}from"./chunk-SCIGZFN5.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-YJBE3IGR.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
2
+ import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-YRCLNWFV.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
3
3
  1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,
4
4
  8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,
5
5
  9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,
@@ -10,14 +10,14 @@ codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullwidth=codePoint=
10
10
  de_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),leadingNonPrintingRegex=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),markCharRegex=new RegExp("^\\p{Mark}$","v"),terminalSpacingMarkRegex=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103\
11
11
  E])+$","v"),rgiEmojiRegex=new RegExp("^\\p{RGI_Emoji}$","v"),WIDTH_CACHE_SIZE=512,widthCache=new Map,cjkBreakRegex=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,cjkPunctuationRegex=new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),autocompleteSeparatorRegex=new RegExp(`\
12
12
  (?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<32||code>126)return!1}return!0}function truncateFragmentToWidth(text,maxWidth){if(maxWidth<=0||text.length===0)return{text:"",width:0};if(isPrintableAscii(text)){let clipped=text.slice(0,maxWidth);return{text:clipped,width:clipped.length}}let hasAnsi=text.includes("\x1B"),
13
- hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of graphemeSegmenter.segment(text)){let w=graphemeWidth(segment);if(width2+w>maxWidth)break;result2+=segment,width2+=w}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",
14
- width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let w=graphemeWidth(segment);if(width+w>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\x1B[0m",hyperlinkClose=getActiveOsc8Close(prefix),
15
- visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function graphemeWidth(segment){if(segment.length===1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;if(couldBeEmoji(
16
- segment)&&rgiEmojiRegex.test(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c2=char.codePointAt(0);followsMark||c2>=65280&&c2<=65519?width+=eastAsianWidth(
17
- c2):(c2===3635||c2===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str);if(cached!==void 0)return cached;let clean=str;str.includes(" ")&&(clean=clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);length>0?(stripped+=
18
- clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of graphemeSegmenter.segment(clean))width+=graphemeWidth(segment);if(widthCache.size>=WIDTH_CACHE_SIZE){let firstKey=widthCache.keys().next().value;firstKey!==void 0&&widthCache.delete(firstKey)}return widthCache.set(str,width),width}function stripTerminalSequences(str){if(!str.includes("\x1B"))return str;
19
- let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}function getGraphemeCellRange(line,column){let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>0&&column>=currentCol&&
20
- column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.
13
+ hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of graphemeSegmenter.segment(text)){let w2=graphemeWidth(segment);if(width2+w2>maxWidth)break;result2+=segment,width2+=w2}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+="\
14
+ ",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let w2=graphemeWidth(segment);if(width+w2>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w2}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\x1B[0m",hyperlinkClose=getActiveOsc8Close(
15
+ prefix),visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function graphemeWidth(segment){if(segment.length===1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;
16
+ if(couldBeEmoji(segment)&&rgiEmojiRegex.test(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c2=char.codePointAt(0);followsMark||c2>=65280&&c2<=65519?
17
+ width+=eastAsianWidth(c2):(c2===3635||c2===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str);if(cached!==void 0)return cached;let clean=str;str.includes(" ")&&(clean=clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);
18
+ length>0?(stripped+=clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of graphemeSegmenter.segment(clean))width+=graphemeWidth(segment);if(widthCache.size>=WIDTH_CACHE_SIZE){let firstKey=widthCache.keys().next().value;firstKey!==void 0&&widthCache.delete(firstKey)}return widthCache.set(str,width),width}function stripTerminalSequences(str){if(!str.
19
+ includes("\x1B"))return str;let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}function getGraphemeCellRange(line,column){let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>
20
+ 0&&column>=currentCol&&column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.
21
21
  segment(line.slice(i,textEnd))){let width=segment===" "?3:graphemeWidth(segment);if(column>=currentCol&&column<currentCol+width)return activeUrl;currentCol+=width}i=textEnd}}var THAI_LAO_AM_REGEX=/[\u0e33\u0eb3]/,THAI_LAO_AM_GLOBAL_REGEX=/[\u0e33\u0eb3]/g;function normalizeTerminalOutput(str){let normalized=str;if(THAI_LAO_AM_REGEX.test(normalized)&&(normalized=normalized.replace(THAI_LAO_AM_GLOBAL_REGEX,char=>char==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!normalized.includes(" "))return normalized;
22
22
  let result="",i=0;for(;i<normalized.length;){let ansi=extractAnsiCode(normalized,i);if(ansi){result+=ansi.code,i+=ansi.length;continue}result+=normalized[i]===" "?" ":normalized[i],i++}return result}function extractAnsiCode(str,pos){let length=ansiCodeLength(str,pos);return length>0?{code:str.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str){let width=0,i=0;for(;i<str.length;){let code=str.charCodeAt(i);if(code>=32&&code<=126)width++,i++;else if(code===9)width+=3,i++;else if(code===
23
23
  27){let length=ansiCodeLength(str,i);if(length===0)return-1;i+=length}else return-1}return width}function ansiCodeLength(str,pos){if(pos>=str.length||str.charCodeAt(pos)!==27)return 0;let next=str[pos+1];if(next==="["){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===109||c2===71||c2===75||c2===72||c2===74)return j2+1-pos}return 0}if(next==="]"||next==="_"){for(let j2=pos+2;j2<str.length;j2++){let c2=str.charCodeAt(j2);if(c2===7)return j2+1-pos;if(c2===27&&str[j2+1]==="\\")
@@ -43,55 +43,58 @@ keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\
43
43
  pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(keepContiguousPrefix&&keptWidth+3<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",keptWidth+=3):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=3,visibleSoFar>maxWidth){overflowed=!0;break}i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let width=graphemeWidth(segment);if(keepContiguousPrefix&&
44
44
  keptWidth+width<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,keptWidth+=width):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}if(overflowed)break;i=end}exhaustedInput=i>=text.length}return!overflowed&&exhaustedInput?pad?text+" ".repeat(Math.max(0,maxWidth-visibleSoFar)):text:finalizeTruncatedResult(result,keptWidth,ellipsis,ellipsisWidth,maxWidth,pad)}function sliceByColumn(line,startCol,length,strict=!1){
45
45
  return sliceWithWidth(line,startCol,length,strict).text}function sliceWithWidth(line,startCol,length,strict=!1){if(length<=0)return{text:"",width:0};let endCol=startCol+length,result="",resultWidth=0,currentCol=0,i=0,pendingAnsi="";for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){currentCol>=startCol&&currentCol<endCol?(result+=pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&(pendingAnsi+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(
46
- line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment),inRange=currentCol>=startCol&&currentCol<endCol,fits=!strict||currentCol+w<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=w),currentCol+=w,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){
47
- let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&&currentCol<afterEnd&&afterStarted&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{
48
- segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment);if(currentCol<beforeEnd&&currentCol+w<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=w):currentCol>=afterStart&&currentCol<afterEnd&&(!strictAfter||currentCol+w<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w),currentCol+=w,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)
49
- break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}var multiply=(m,[x2,y2,z2])=>m.map(row=>row[0]*x2+row[1]*y2+row[2]*z2),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,
46
+ line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w2=graphemeWidth(segment),inRange=currentCol>=startCol&&currentCol<endCol,fits=!strict||currentCol+w2<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=w2),currentCol+=w2,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){
47
+ let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&&currentCol<afterEnd&&(afterStarted||ansi.code.startsWith("\x1B_"))&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(
48
+ line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w2=graphemeWidth(segment);if(currentCol<beforeEnd&&currentCol+w2<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=w2):currentCol>=afterStart&&currentCol<afterEnd&&(!strictAfter||currentCol+w2<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w2),currentCol+=w2,afterLen<=0?currentCol>=
49
+ beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}var multiply=(m,[x2,y2,z2])=>m.map(row=>row[0]*x2+row[1]*y2+row[2]*z2),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,
50
50
  -.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,
51
51
  .00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(
52
- LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b}){return linearSrgbToOklab([r/255,g/255,b/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b}}function lmsSlopes(a,b){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b)}function maxSaturation(a,b){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],
53
- weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b+k3*a*a+k4*a*b,slopes=lmsSlopes(a,b),base=slopes.map(k5=>1+saturation*k5),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f2=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f*f1/(f1*f1-.5*f*f2)}function cusp(a,b){let saturation=maxSaturation(a,b),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([
54
- 1,saturation*a,saturation*b])));return[lightness,lightness*saturation]}function maxChroma(a,b,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b),lms=slopes.map(k2=>lightness+t*k2),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(
55
- row=>{let f=dot(row,cubes)-1,f1=dot(row,first),f2=dot(row,second),u=f1/(f1*f1-.5*f*f2);return u>=0?-f*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b){let peak=cusp(a,b),cMax=maxChroma(a,b,L2,peak),k2=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b+a*(-2.19557347+1.75198401*b+a*(-2.13704948-10.02301043*b+a*(-4.24894561+5.38770819*b+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b+a*(.40370612+.90148123*
56
- b+a*(-.27087943+.6122399*b+a*(.00299215-.45399568*b-.14661872*a)))),cMid=.9*k2*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;
57
- chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),
58
- saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b){for(let[name,value]of[["r",r],["g",g],["b",b]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.
59
- freeze({kind:"rgb",r,g,b})}function oklchColor(l3,c2,h2){if(requireFinite(l3,"l"),requireFinite(c2,"c"),requireFinite(h2,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c2<0)throw new Error(`c must not be negative: ${c2}`);return Object.freeze({kind:"oklch",l:l3,c:c2,h:(h2%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg\
60
- )?\\s*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h2,s,l3){if(requireFinite(h2,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);let{r,g,b}=okhslToRgb(h2,s,l3);return rgbColor(r,g,b)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){
52
+ LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b}){return linearSrgbToOklab([r/255,g/255,b/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b}}function lmsSlopes(a3,b){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a3+row[2]*b)}function maxSaturation(a3,b){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a3+y2*b>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],
53
+ weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a3+k2*b+k3*a3*a3+k4*a3*b,slopes=lmsSlopes(a3,b),base=slopes.map(k=>1+saturation*k),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f2=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f22=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f2*f1/(f1*f1-.5*f2*f22)}function cusp(a3,b){let saturation=maxSaturation(a3,b),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb(
54
+ [1,saturation*a3,saturation*b])));return[lightness,lightness*saturation]}function maxChroma(a3,b,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a3,b),lms=slopes.map(k=>lightness+t*k),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(
55
+ row=>{let f2=dot(row,cubes)-1,f1=dot(row,first),f22=dot(row,second),u=f1/(f1*f1-.5*f2*f22);return u>=0?-f2*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a3,b){let peak=cusp(a3,b),cMax=maxChroma(a3,b,L2,peak),k=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b+a3*(-2.19557347+1.75198401*b+a3*(-2.13704948-10.02301043*b+a3*(-4.24894561+5.38770819*b+4.69891013*a3)))),midT=.11239642+1/(1.6132032-.68124379*b+a3*(.40370612+
56
+ .90148123*b+a3*(-.27087943+.6122399*b+a3*(.00299215-.45399568*b-.14661872*a3)))),cMid=.9*k*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a3=Math.cos(angle),b=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a3,b),chroma;if(saturation<.8){let t=1.25*saturation,
57
+ k1=.8*c0;chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a3,chroma*b]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/
58
+ chroma),saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b){for(let[name,value]of[["r",r],["g",g],["b",b]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.
59
+ freeze({kind:"rgb",r,g,b})}function oklchColor(l,c2,h2){if(requireFinite(l,"l"),requireFinite(c2,"c"),requireFinite(h2,"h"),l<0||l>1)throw new Error(`l must be between 0 and 1: ${l}`);if(c2<0)throw new Error(`c must not be negative: ${c2}`);return Object.freeze({kind:"oklch",l,c:c2,h:(h2%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`,
60
+ "i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h2,s,l){if(requireFinite(h2,"h"),requireFinite(s,"s"),requireFinite(l,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l<0||l>1)throw new Error(`l must be between 0 and 1: ${l}`);let{r,g,b}=okhslToRgb(h2,s,l);return rgbColor(r,g,b)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){
61
61
  if(typeof value=="number")return indexedColor(value);let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(
62
62
  oklch[4]))}let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,
63
63
  g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.
64
- every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c:c2,h:h2}){let radians=h2*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c2);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c2;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(
65
- linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b),h:(Math.atan2(b,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(
66
- 2,"0");return`#${channel(r)}${channel(g)}${channel(b)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b2=colorToRgb(second);return rgbColor(a2.r+(b2.r-a2.r)*amount,a2.g+(b2.g-a2.g)*amount,a2.b+(b2.b-a2.b)*amount)}let a=colorToOklch(first),b=colorToOklch(second),firstHue=a.c<1e-7?b.h:a.h,hueDelta=((b.c<1e-7?firstHue:b.h)-firstHue+540)%
67
- 360-180;return oklchColor(a.l+(b.l-a.l)*amount,a.c+(b.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){
68
- let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<
69
- colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,
70
- !0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+=
71
- "\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",
64
+ every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l,c:c2,h:h2}){let radians=h2*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l,chroma*cos,chroma*sin]),direct=atChroma(c2);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c2;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(
65
+ linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l,a3,b]=rgbToOklab(colorToRgb(color));return{l,c:Math.hypot(a3,b),h:(Math.atan2(b,a3)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(
66
+ 2,"0");return`#${channel(r)}${channel(g)}${channel(b)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a4=colorToRgb(first),b2=colorToRgb(second);return rgbColor(a4.r+(b2.r-a4.r)*amount,a4.g+(b2.g-a4.g)*amount,a4.b+(b2.b-a4.b)*amount)}let a3=colorToOklch(first),b=colorToOklch(second),firstHue=a3.c<1e-7?b.h:a3.h,hueDelta=((b.c<1e-7?firstHue:b.h)-firstHue+
67
+ 540)%360-180;return oklchColor(a3.l+(b.l-a3.l)*amount,a3.c+(b.c-a3.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}
68
+ function rgbToAnsi256(color){let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,
69
+ {r:grayValue,g:grayValue,b:grayValue})<colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){
70
+ return colorAnsi(color,mode,!0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),
71
+ options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",
72
72
  f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:key=>`ctrl+${key}`,shift:key=>`shift+${key}`,alt:key=>`alt+${key}`,super:key=>`super+${key}`,
73
73
  ctrlShift:key=>`ctrl+shift+${key}`,shiftCtrl:key=>`shift+ctrl+${key}`,ctrlAlt:key=>`ctrl+alt+${key}`,altCtrl:key=>`alt+ctrl+${key}`,shiftAlt:key=>`shift+alt+${key}`,altShift:key=>`alt+shift+${key}`,ctrlSuper:key=>`ctrl+super+${key}`,superCtrl:key=>`super+ctrl+${key}`,shiftSuper:key=>`shift+super+${key}`,superShift:key=>`super+shift+${key}`,altSuper:key=>`alt+super+${key}`,superAlt:key=>`super+alt+${key}`,ctrlShiftAlt:key=>`ctrl+shift+alt+${key}`,ctrlShiftSuper:key=>`ctrl+shift+super+${key}`},SYMBOL_KEYS=new Set(
74
- ["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],
75
- [57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],[57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.delete]]);function normalizeKittyFunctionalCodepoint(codepoint){
76
- return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=65&&codepoint<=90?codepoint+32:codepoint}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5\
77
- ~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:[
78
- "\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B\
79
- [2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"\
80
- f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===
81
- MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(
82
- ":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F"))}function parseEventType(eventTypeStr){if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}function parseKittySequence(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(csiUMatch){let codepoint=parseInt(csiUMatch[1],
83
- 10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),eventType=parseEventType(arrowMatch[2]),arrowCodes={
84
- A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.
85
- end}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){
86
- let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK;if(actualMod!==expectedMod)return!1;let normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(normalizedCodepoint===normalizedExpectedCodepoint)return!0;
87
- if(parsed.baseLayoutKey!==void 0&&parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}function parseModifyOtherKeysSequence(data){let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){
88
- let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.
89
- toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){if(expectedModifier===0)return!1;let parsed=parseModifyOtherKeysSequence(data);return!parsed||parsed.modifier!==expectedModifier?!1:normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===
90
- normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier)}function formatKeyNameWithModifiers(keyName,modifier){let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.super&&mods.push("super"),mods.
91
- length>0?`${mods.join("+")}+${keyName}`:keyName}function parseKeyId(keyId){let parts=keyId.toLowerCase().split("+"),key=parts[parts.length-1];return key?{key,ctrl:parts.includes("ctrl"),shift:parts.includes("shift"),alt:parts.includes("alt"),super:parts.includes("super")}:null}function matchesKey(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)return!1;let{key,ctrl,shift,alt,super:superModifier}=parsed,modifier=0;switch(shift&&(modifier|=MODIFIERS.shift),alt&&(modifier|=MODIFIERS.alt),ctrl&&
92
- (modifier|=MODIFIERS.ctrl),superModifier&&(modifier|=MODIFIERS.super),key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(
93
- data,CODEPOINTS.space,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?
94
- matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
74
+ ["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),SHIFTED_SYMBOL_KEYS=new Set("~!@#$%^&*()_+|{}:<>?"),MODIFIER_NAMES=["shift","alt","ctrl","super"],MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map(
75
+ [[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],[57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.
76
+ delete]]);function normalizeKittyFunctionalCodepoint(codepoint){return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=65&&codepoint<=90?codepoint+32:codepoint}function getLogicalShiftedSymbolCandidate(codepoint,modifier,allowedSymbols){if(codepoint===void 0||(modifier&MODIFIERS.shift)===0)return;let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint);
77
+ if(allowedSymbols.has(String.fromCharCode(normalizedCodepoint)))return{codepoint:normalizedCodepoint,modifier:modifier&~MODIFIERS.shift}}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~",
78
+ "\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:[
79
+ "\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delet\
80
+ e","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"\
81
+ f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):
82
+ modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":\
83
+ 2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F"))}function parseEventType(eventTypeStr){if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}var lastKittyData,lastKittySequence=null;function parseKittySequence(data){return data!==lastKittyData?(lastKittySequence=parseKittySequenceUncached(data),lastKittyData=data):lastKittySequence&&(_lastEventType=lastKittySequence.eventType),
84
+ lastKittySequence}function parseKittySequenceUncached(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(csiUMatch){let codepoint=parseInt(csiUMatch[1],10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-
85
+ 1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),eventType=parseEventType(arrowMatch[2]),arrowCodes={A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),
86
+ codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.end}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.
87
+ home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK,normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(
88
+ normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(actualMod===expectedMod&&normalizedCodepoint===normalizedExpectedCodepoint)return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.shiftedKey,actualMod,SYMBOL_KEYS);if(logicalShiftedSymbol&&(logicalShiftedSymbol.modifier&~LOCK_MASK)===expectedMod&&logicalShiftedSymbol.codepoint===normalizeKittyFunctionalCodepoint(expectedCodepoint))return!0;if(actualMod!==expectedMod)return!1;if(parsed.baseLayoutKey!==void 0&&
89
+ parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}var lastModifyOtherKeysData,lastModifyOtherKeysSequence=null;function parseModifyOtherKeysSequence(data){return data!==lastModifyOtherKeysData&&(lastModifyOtherKeysSequence=parseModifyOtherKeysSequenceUncached(data),lastModifyOtherKeysData=data),lastModifyOtherKeysSequence}function parseModifyOtherKeysSequenceUncached(data){
90
+ let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.
91
+ env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){
92
+ let parsed=parseModifyOtherKeysSequence(data);if(!parsed)return!1;if(parsed.modifier===expectedModifier&&normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier))return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.codepoint,parsed.modifier,SHIFTED_SYMBOL_KEYS);return logicalShiftedSymbol?.modifier===expectedModifier&&logicalShiftedSymbol.codepoint===expectedKeycode}function formatKeyNameWithModifiers(keyName,modifier){
93
+ let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.super&&mods.push("super"),mods.length>0?`${mods.join("+")}+${keyName}`:keyName}var parsedKeyIds=new Map,MAX_PARSED_KEY_IDS=512;function parseKeyId(keyId){let parsed=parsedKeyIds.
94
+ get(keyId);return parsed===void 0&&(parsed=parseKeyIdUncached(keyId),parsedKeyIds.size>=MAX_PARSED_KEY_IDS&&parsedKeyIds.clear(),parsedKeyIds.set(keyId,parsed)),parsed}function parseKeyIdUncached(keyId){let key=keyId.toLowerCase(),modifiers=new Set;for(;;){let modifier2=MODIFIER_NAMES.find(name=>key.startsWith(`${name}+`));if(!modifier2)break;if(modifiers.has(modifier2))return null;modifiers.add(modifier2),key=key.slice(modifier2.length+1)}if(!key||key.includes("+")&&key!=="+")return null;let modifier=0;
95
+ return modifiers.has("shift")&&(modifier|=MODIFIERS.shift),modifiers.has("alt")&&(modifier|=MODIFIERS.alt),modifiers.has("ctrl")&&(modifier|=MODIFIERS.ctrl),modifiers.has("super")&&(modifier|=MODIFIERS.super),{key,modifier}}function matchesKey(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)return!1;let{key,modifier}=parsed;switch(key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"\
96
+ space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(data,CODEPOINTS.space,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.
97
+ tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
95
98
  `:!1:modifier===MODIFIERS.alt?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.alt)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.alt)?!0:_kittyProtocolActive?!1:data==="\x1B\r":modifier===0?data==="\r"||!_kittyProtocolActive&&data===`
96
99
  `||data==="\x1BOM"||matchesKittySequence(data,CODEPOINTS.enter,0)||matchesKittySequence(data,CODEPOINTS.kpEnter,0):matchesKittySequence(data,CODEPOINTS.enter,modifier)||matchesKittySequence(data,CODEPOINTS.kpEnter,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.enter,modifier);case"backspace":return modifier===MODIFIERS.alt?data==="\x1B\x7F"||data==="\x1B\b"?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.alt):modifier===
97
100
  MODIFIERS.ctrl?matchesRawBackspace(data,MODIFIERS.ctrl)?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.ctrl)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.ctrl):modifier===0?matchesRawBackspace(data,0)||matchesKittySequence(data,CODEPOINTS.backspace,0)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,0):matchesKittySequence(data,CODEPOINTS.backspace,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,modifier);case"insert":return modifier===0?matchesLegacySequence(
@@ -104,11 +107,12 @@ left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyM
104
107
  data==="\x1BF"||data==="\x1Bf"||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5C"||matchesLegacyModifierSequence(data,"right",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.right)||matchesKittySequence(data,ARROW_CODEPOINTS.right,0):matchesLegacyModifierSequence(data,"right",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.right,modifier);case"\
105
108
  f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return modifier!==0?!1:matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[key])}if(key.length===1&&(key>="a"&&key<="z"||isDigitKey(key)||SYMBOL_KEYS.has(key))){let codepoint=key.charCodeAt(0),rawCtrl=rawCtrlChar(key),isLetter=key>="a"&&key<="z",isDigit=isDigitKey(key);return modifier===MODIFIERS.ctrl+MODIFIERS.alt&&!_kittyProtocolActive&&rawCtrl&&data===`\x1B${rawCtrl}`||modifier===MODIFIERS.alt&&
106
109
  !_kittyProtocolActive&&(isLetter||isDigit||SYMBOL_KEYS.has(key))&&data===`\x1B${key}`?!0:modifier===MODIFIERS.ctrl?rawCtrl&&data===rawCtrl?!0:matchesKittySequence(data,codepoint,MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.ctrl):modifier===MODIFIERS.shift+MODIFIERS.ctrl?matchesKittySequence(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl):modifier===MODIFIERS.shift?isLetter&&data===key.toUpperCase()?
107
- !0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint,
108
- modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName="escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.kpEnter?keyName=
109
- "enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageDown?
110
- keyName="pageDown":effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(
111
- keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty)return formatParsedKey(kitty.codepoint,kitty.modifier,kitty.baseLayoutKey);let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys)return formatParsedKey(modifyOtherKeys.codepoint,modifyOtherKeys.modifier);if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
110
+ !0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)||matchesPrintableModifyOtherKeys(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(
111
+ normalizedCodepoint,modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName="escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.
112
+ kpEnter?keyName="enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.
113
+ pageDown?keyName="pageDown":effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(
114
+ keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(kitty.shiftedKey,kitty.modifier,SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??kitty.codepoint,logicalShiftedSymbol?.modifier??kitty.modifier,kitty.baseLayoutKey)}let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint,modifyOtherKeys.
115
+ modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
112
116
  `))return"shift+enter";let legacySequenceKeyId=LEGACY_SEQUENCE_KEY_IDS[data];if(legacySequenceKeyId)return legacySequenceKeyId;if(data==="\x1B")return"escape";if(data==="")return"ctrl+\\";if(data==="")return"ctrl+]";if(data==="")return"ctrl+-";if(data==="\x1B\x1B")return"ctrl+alt+[";if(data==="\x1B")return"ctrl+alt+\\";if(data==="\x1B")return"ctrl+alt+]";if(data==="\x1B")return"ctrl+alt+-";if(data===" ")return"tab";if(data==="\r"||!_kittyProtocolActive&&data===`
113
117
  `||data==="\x1BOM")return"enter";if(data==="\0")return"ctrl+space";if(data===" ")return"space";if(data==="\x7F")return"backspace";if(data==="\b")return isWindowsTerminalSession()?"ctrl+backspace":"backspace";if(data==="\x1B[Z")return"shift+tab";if(!_kittyProtocolActive&&data==="\x1B\r")return"alt+enter";if(!_kittyProtocolActive&&data==="\x1B ")return"alt+space";if(data==="\x1B\x7F"||data==="\x1B\b")return"alt+backspace";if(!_kittyProtocolActive&&data==="\x1BB")return"alt+left";if(!_kittyProtocolActive&&
114
118
  data==="\x1BF")return"alt+right";if(!_kittyProtocolActive&&data.length===2&&data[0]==="\x1B"){let code=data.charCodeAt(1);if(code>=1&&code<=26)return`ctrl+alt+${String.fromCharCode(code+96)}`;let key=String.fromCharCode(code);if(code>=97&&code<=122||code>=48&&code<=57||SYMBOL_KEYS.has(key))return`alt+${key}`}if(data==="\x1B[A")return"up";if(data==="\x1B[B")return"down";if(data==="\x1B[C")return"right";if(data==="\x1B[D")return"left";if(data==="\x1B[H"||data==="\x1BOH")return"home";if(data==="\x1B[F"||
@@ -127,153 +131,155 @@ p":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen
127
131
  definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.
128
132
  entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.
129
133
  keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(
130
- TUI_KEYBINDINGS)),globalKeybindings}var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>F,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,
134
+ TUI_KEYBINDINGS)),globalKeybindings}var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>U,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,
131
135
  SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,
132
136
  decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,
133
137
  getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,invalidateRenderedMarkdown:()=>invalidateRenderedMarkdown,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,
134
- isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderImage:()=>renderImage,renderLatex:()=>renderLatex,resetCapabilitiesCache:()=>resetCapabilitiesCache,
135
- rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function I(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P=I();function W(l3){P=l3}var A={exec:()=>null};function C(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function h(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}
136
- var _e=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,
138
+ isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isStableRender:()=>isStableRender,isViewportTUI:()=>isViewportTUI,markStableRender:()=>markStableRender,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,onCapabilitiesChange:()=>onCapabilitiesChange,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,
139
+ renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,renderSharedLines:()=>renderSharedLines,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,
140
+ styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function B(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var y=B();function V(a3){y=a3}var M={exec:()=>null};function D(a3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=a3(n),e[n]=i),i}}function h(a3,e=""){let t=typeof a3=="string"?a3:a3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}
141
+ var ze=((a3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+a3)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,
137
142
  blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,
138
- endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,
139
- slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:C(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:C(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:C(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:C(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:C(
140
- l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${N})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:C(l3=>new RegExp(`^ {0,${l3}}>`))},$e=/^(?:[ \t]*(?:\n|$))+/,Le=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ze=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,G=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ae=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,J=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,he=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
141
- de=h(he).replace(/bull/g,J).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ee=h(he).replace(/bull/g,J).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,
142
- / {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),V=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Me=/^[^\n]+/,Y=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ie=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Y).replace("ti\
143
- tle",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ce=h(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,J).getRegex(),N="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|u\
144
- l",ee=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Be=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))",
145
- "i").replace("comment",ee).replace("tag",N).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ke=l3=>h(V).replace("hr",G).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N).getRegex(),
146
- De=ke(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),qe=ke(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),ve=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",qe).getRegex(),te={blockquote:ve,code:Le,def:Ie,fences:ze,heading:Ae,hr:G,html:Be,lheading:de,list:Ce,newline:$e,paragraph:De,table:A,text:Me},ue=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",G).replace("head\
147
- ing"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N).getRegex(),Ze={...te,lheading:Ee,table:ue,paragraph:h(V).replace("hr",G).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ue).replace("blockquote",
148
- " {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",N).getRegex()},He={...te,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ee).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|cod\
149
- e|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:A,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(V).replace("hr",G).replace("heading",` *#{1,6} *[^
150
- ]`).replace("lheading",de).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ge=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ne=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ge=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Qe=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,$=/[\p{P}\p{S}]/u,B=/[\s\p{P}\p{S}]/u,Q=/[^\s\p{P}\p{S}]/u,je=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,B).getRegex(),
151
- Fe=/[\p{Pi}\p{Ps}"']/u,fe=/(?!~)[\p{P}\p{S}]/u,Ue=/(?!~)[\s\p{P}\p{S}]/u,Ke=/(?:[^\s\p{P}\p{S}]|~)/u,We=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",_e?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),me=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Xe=h(me,"u").replace(/punct/g,$).getRegex(),Je=h(
152
- me,"u").replace(/punct/g,fe).getRegex(),Ve=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Ye=h(Ve,"u").replace(/openQuote/g,Fe).replace(/punct/g,$).getRegex(),xe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",et=h(xe,"gu").replace(/notPunctSpace/g,
153
- Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),tt=h(xe,"gu").replace(/notPunctSpace/g,Ke).replace(/punctSpace/g,Ue).replace(/punct/g,fe).getRegex(),nt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",rt=h(nt,"gu").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,
154
- B).replace(/punct/g,$).getRegex(),st=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),it="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!\
155
- _)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",ot=h(it,"gu").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),at=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,$).getRegex(),lt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ut=h(lt,"gu").replace(
156
- /notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),pt=h(/\\(punct)/,"gu").replace(/punct/g,$).getRegex(),ct=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ht=h(ee).replace("(?:-->|$)","-->").getRegex(),dt=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA\
157
- -Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ht).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),be=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,U=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",be).getRegex(),kt=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).
158
- replace("label",U).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",U).replace("ref",Y).getRegex(),ft=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",Y).getRegex(),pe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,mt=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",be).
159
- getRegex(),xt=h("reflink|nolink(?!\\()","g").replace("reflink",h(/^!?\[(label)\]\[(ref)\]/).replace("label",mt).replace("ref",pe).getRegex()).replace("nolink",h(/^!?\[(ref)\](?:\[\])?/).replace("ref",pe).getRegex()).getRegex(),ce=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,Rt=h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,bt).getRegex(),ne={_backpedal:A,anyPunctuation:pt,autolink:ct,blockSkip:We,br:ge,
160
- code:Ne,del:A,delLDelim:A,delRDelim:A,emStrongLDelim:Xe,emStrongRDelimAst:et,emStrongRDelimUnd:st,escape:Ge,link:kt,nolink:ft,punctuation:je,reflink:gt,reflinkSearch:xt,tag:dt,text:Qe,url:A},Tt={...ne,emStrongLDelim:Ye,emStrongRDelimAst:rt,emStrongRDelimUnd:ot,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",U).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",U).getRegex()},X={...ne,emStrongRDelimAst:tt,emStrongLDelim:Je,delLDelim:at,delRDelim:ut,url:h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).
161
- replace("emailProtocol",Rt).replace("protocol",ce).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).
162
- replace("protocol",ce).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},Ot={...X,br:h(ge).replace("{2,}","*").getRegex(),text:h(X.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},j={normal:te,gfm:Ze,pedantic:He},D={normal:ne,gfm:X,breaks:Ot,pedantic:Tt},wt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Re=l3=>wt[l3];function O(l3,e){if(e){if(x.escapeTest.test(l3))return l3.replace(x.escapeReplace,Re)}else if(x.escapeTestNoEncode.test(l3))return l3.replace(
163
- x.escapeReplaceNoEncode,Re);return l3}function Te(l3){return l3.replace(x.numericCharacterReference,(e,t,n)=>{let s=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return s===0||s>1114111||s>=55296&&s<=57343?"\uFFFD":String.fromCodePoint(s)})}function re(l3){try{l3=encodeURI(l3).replace(x.percentDecode,"%")}catch{return null}return l3}function se(l3,e){let t=l3.replace(x.findPipe,(r,o,i)=>{let u=!1,a=o;for(;--a>=0&&i[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(x.splitPipe),s=0;if(n[0].trim()||
164
- n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(x.slashPipe,"|");return n}function L(l3,e,t){let n=l3.length;if(n===0)return"";let s=0;for(;s<n;){let r=l3.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l3.slice(0,n-s)}function ie(l3){let e=l3.split(`
165
- `),t=e.length-1;for(;t>=0&&x.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
166
- `)}function q(l3){return l3.trim().toLowerCase().toUpperCase().toLowerCase()}function oe(l3,e){if(l3.indexOf(e[0])===-1&&l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function ae(l3,e=0){let t=e,n="";for(let s of l3)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function Oe(l3,e,t,n,s){let r=e.href,o=e.title||null,i=l3[1].replace(s.other.outputLinkReplace,
167
- "$1"),u=l3[0].charAt(0)==="!";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c2=n.inlineTokens(i),d=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(d){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:t,href:r,title:o,text:i,tokens:c2}}function Pt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
168
- `).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[i]=o;return r.slice(Math.min(i.length,s.length))}).join(`
169
- `)}function we(l3,e,t,n){if(!e.includes("<"))return!1;for(let s=0;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]==="`"){let i=n.inline.code.exec(e.slice(s));if(i){s+=i[0].length-1;continue}}if(e[s]!=="<")continue;let r=l3.slice(t+s),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-s)return!0;s+=o[0].length-1}}return!1}var y=class{options;rules;lexer;constructor(e){this.options=e||P}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"\
170
- space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ie(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Pt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.
171
- rules.other.endingHash.test(n)){let s=L(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:L(t[0],`
172
- `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:L(t[0],`
173
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],`
143
+ endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
144
+ caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:a3=>new RegExp(`^( {0,3}${a3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:D(a3=>new RegExp(`^ {0,${a3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:\`\`\`\
145
+ |~~~)`)),headingBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}#`)),htmlBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:</?(?:${Q})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}>`))},Ee=/^(?:[ \t]*(?:\n|$))+/,Me=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ce=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,N=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
146
+ Ie=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Y=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,me=h(fe).replace(/bull/g,Y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).
147
+ replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Be=h(fe).replace(/bull/g,Y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ee=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,
148
+ De=/^[^\n]+/,te=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qe=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",te).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ze=h(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Y).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form\
149
+ |frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ne=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ve=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script\
150
+ |pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ne).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xe=a3=>h(ee).replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").
151
+ replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",a3).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),He=xe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ge=xe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ne=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ge).getRegex(),re={blockquote:Ne,code:Me,def:qe,fences:Ce,heading:Ie,hr:N,html:ve,
152
+ lheading:me,list:Ze,newline:Ee,paragraph:He,table:M,text:De},de=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,\
153
+ 3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),Qe={...re,lheading:Be,table:de,paragraph:h(ee).replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",de).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\\
154
+ n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex()},je={...re,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ne).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
155
+ heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:M,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(ee).replace("hr",N).replace("heading",` *#{1,6} *[^
156
+ ]`).replace("lheading",me).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ue=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,be=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ke=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,S=/[\p{P}\p{S}]/u,q=/[\s\p{P}\p{S}]/u,j=/[^\s\p{P}\p{S}]/u,Xe=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,q).getRegex(),
157
+ We=/[\p{Pi}\p{Ps}"']/u,Re=/(?!~)[\p{P}\p{S}]/u,Ve=/(?!~)[\s\p{P}\p{S}]/u,Je=/(?:[^\s\p{P}\p{S}]|~)/u,Ye=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ze?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Te=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,et=h(Te,"u").replace(/punct/g,S).getRegex(),tt=h(
158
+ Te,"u").replace(/punct/g,Re).getRegex(),nt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,rt=h(nt,"u").replace(/openQuote/g,We).replace(/punct/g,S).getRegex(),Oe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",st=h(Oe,"gu").replace(/notPunctSpace/g,
159
+ j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),it=h(Oe,"gu").replace(/notPunctSpace/g,Je).replace(/punctSpace/g,Ve).replace(/punct/g,Re).getRegex(),ot="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",at=h(ot,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,
160
+ q).replace(/punct/g,S).getRegex(),lt=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),ut="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!\
161
+ _)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pt=h(ut,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),ct=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,S).getRegex(),ht="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",dt=h(ht,"gu").replace(
162
+ /notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),kt=h(/\\(punct)/,"gu").replace(/punct/g,S).getRegex(),gt=h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,S).getRegex(),ft=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),mt=h(ne).replace(
163
+ "(?:-->|$)","-->").getRegex(),xt=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",mt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),we=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,K=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",we).getRegex(),
164
+ bt=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",K).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",K).replace("ref",te).getRegex(),Tt=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",te).getRegex(),ke=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Ot=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).
165
+ replace("brackets",we).getRegex(),wt=h("reflink|nolink(?!\\()","g").replace("reflink",h(/^!?\[(label)\]\[(ref)\]/).replace("label",Ot).replace("ref",ke).getRegex()).replace("nolink",h(/^!?\[(ref)\](?:\[\])?/).replace("ref",ke).getRegex()).getRegex(),ge=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,yt=h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Pt).getRegex(),se={_backpedal:M,anyPunctuation:kt,anyPunctuationOutsideCode:gt,
166
+ autolink:ft,blockSkip:Ye,br:be,code:Ue,del:M,delLDelim:M,delRDelim:M,emStrongLDelim:et,emStrongRDelimAst:st,emStrongRDelimUnd:lt,escape:Fe,link:bt,nolink:Tt,punctuation:Xe,reflink:Rt,reflinkSearch:wt,tag:xt,text:Ke,url:M},St={...se,emStrongLDelim:rt,emStrongRDelimAst:at,emStrongRDelimUnd:pt,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",K).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",K).getRegex()},J={...se,emStrongRDelimAst:it,emStrongLDelim:tt,delLDelim:ct,delRDelim:dt,
167
+ url:h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",yt).replace("protocol",ge).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).
168
+ replace("protocol",ge).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},_t={...J,br:h(be).replace("{2,}","*").getRegex(),text:h(J.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},F={normal:re,gfm:Qe,pedantic:je},Z={normal:se,gfm:J,breaks:_t,pedantic:St},$t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Pe=a3=>$t[a3];function w(a3,e){if(e){if(x.escapeTest.test(a3))return a3.replace(x.escapeReplace,Pe)}else if(x.escapeTestNoEncode.test(a3))return a3.replace(
169
+ x.escapeReplaceNoEncode,Pe);return a3}function ye(a3){return x.numericCharacterReference.test(a3)?a3.replace(x.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return"&amp;";let i=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return i===0||i>1114111||i>=55296&&i<=57343?"\uFFFD":i===38?"&amp;":String.fromCodePoint(i)}):a3}function ie(a3){try{a3=encodeURI(a3).replace(x.percentDecode,"%")}catch{return null}return a3}function oe(a3,e){let t=a3.replace(x.findPipe,(r,o,s)=>{
170
+ let l=!1,u=o;for(;--u>=0&&s[u]==="\\";)l=!l;return l?"|":" |"}),n=t.split(x.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(x.slashPipe,"|");return n}function A(a3,e,t){let n=a3.length;if(n===0)return"";let i=0;for(;i<n;){let r=a3.charAt(n-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return a3.slice(0,n-i)}function ae(a3){let e=a3.split(`
171
+ `),t=e.length-1;for(;t>=0&&x.blankLine.test(e[t]);)t--;return e.length-t<=2?a3:e.slice(0,t+1).join(`
172
+ `)}function v(a3){return a3.trim().toLowerCase().toUpperCase().toLowerCase()}function le(a3,e){if(a3.indexOf(e[0])===-1&&a3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<a3.length;n++)if(a3[n]==="\\")n++;else if(a3[n]===e[0])t++;else if(a3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function X(a3,e=0){let t=e,n="";for(let i of a3)if(i===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=i,t++;return n}function Se(a3,e,t,n,i){let r=e.href,o=e.title||null,s=a3[1].replace(i.other.outputLinkReplace,
173
+ "$1"),l=a3[0].charAt(0)==="!",u=n.state.inLink,c2=n.state.linkEmitted,p=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(s),g=n.state.linkEmitted;if(n.state.linkEmitted=c2,n.state.inLink=u,!l){if(g){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:t,href:r,title:o,text:s,tokens:d}}function Lt(a3,e,t){let n=a3.match(t.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
174
+ `).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[s]=o;return r.slice(Math.min(s.length,i.length))}).join(`
175
+ `)}function _e(a3,e,t,n){if(!e.includes("<"))return!1;for(let i=0;i<e.length;i++){if(e[i]==="\\"){i++;continue}if(e[i]==="`"){let s=n.inline.code.exec(e.slice(i));if(s){i+=s[0].length-1;continue}}if(e[i]!=="<")continue;let r=a3.slice(t+i),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-i)return!0;i+=o[0].length-1}}return!1}var _=class{options;rules;lexer;constructor(e){this.options=e||y}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"\
176
+ space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ae(t[0]),i=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=Lt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.
177
+ rules.other.endingHash.test(n)){let i=A(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceTabChar.test(i))&&(n=i.trim())}return{type:"heading",raw:A(t[0],`
178
+ `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:A(t[0],`
179
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=A(t[0],`
174
180
  `).split(`
175
- `),s="",r="",o=[];for(;n.length>0;){let i=!1,u=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))u.push(n[a]),i=!0;else if(!i)u.push(n[a]);else break;n=n.slice(a);let p=u.join(`
176
- `),c2=p.replace(this.rules.other.blockquoteSetextReplace,`
177
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
178
- ${p}`:p,r=r?`${r}
179
- ${c2}`:c2;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c2,o,!0),this.lexer.state.top=d,n.length===0)break;let m=o.at(-1);if(m?.type==="code")break;if(m?.type==="blockquote"){let b=m,g=n.join(`
180
- `),w=b.raw+`
181
- `+g.replace(this.rules.other.blockquoteSetextReplace2,""),f=this.blockquote(w);o[o.length-1]=f;let M=w.substring(f.raw.length).replace(/^\n/,""),v=M?M.split(`
182
- `).length:0,Z=v?n.slice(0,-v):n;Z.length>0&&(s=`${s}
183
- ${Z.join(`
184
- `)}`),r=r.substring(0,r.length-b.text.length)+f.text;break}else if(m?.type==="list"){let b=m,g=b.raw+`
181
+ `),i="",r="",o=[];for(;n.length>0;){let s=!1,l=[],u;for(u=0;u<n.length;u++)if(this.rules.other.blockquoteStart.test(n[u]))l.push(n[u]),s=!0;else if(!s)l.push(n[u]);else break;n=n.slice(u);let c2=l.join(`
182
+ `),p=c2.replace(this.rules.other.blockquoteSetextReplace,`
183
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
184
+ ${c2}`:c2,r=r?`${r}
185
+ ${p}`:p;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,o,!0),this.lexer.state.top=d,n.length===0)break;let g=o.at(-1);if(g?.type==="code"||g?.type==="heading"||g?.type==="hr"||g?.type==="html")break;if(g?.type==="blockquote"){let k=g,P=n.join(`
186
+ `),R=k.raw+`
187
+ `+P.replace(this.rules.other.blockquoteSetextReplace2,""),m=this.blockquote(R);o[o.length-1]=m;let E=R.substring(m.raw.length).replace(/^\n/,""),b=E?E.split(`
188
+ `).length:0,H=b?n.slice(0,-b):n;H.length>0&&(i=`${i}
189
+ ${H.join(`
190
+ `)}`),r=r.substring(0,r.length-k.text.length)+m.text;break}else if(g?.type==="list"){let k=g,P=k.raw+`
185
191
  `+n.join(`
186
- `),w=this.list(g);o[o.length-1]=w,s=s.substring(0,s.length-m.raw.length)+w.raw,r=r.substring(0,r.length-b.raw.length)+w.raw,n=g.substring(o.at(-1).raw.length).split(`
187
- `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let o=this.rules.other.listItemRegex(n),i=!1;for(;e;){let a=!1,p="",c2="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=t[2].split(`
188
- `,1)[0],m=t[1].length,b=this.options.pedantic?ae(d,m):d.replace(this.rules.other.leadingSpaceTab,M=>ae(M,m)),g=e.split(`
189
- `,1)[0],w=!b.trim(),f=0;if(this.options.pedantic?(f=2,c2=b.trimStart()):w?f=m+1:(f=b.search(this.rules.other.nonSpaceChar),f=f>4?1:f,c2=b.slice(f),f+=m),w&&this.rules.other.blankLine.test(g)&&(p+=g+`
190
- `,e=e.substring(g.length+1),a=!0),!a){let M=this.rules.other.nextBulletRegex(f),v=this.rules.other.hrRegex(f),Z=this.rules.other.fencesBeginRegex(f),le=this.rules.other.headingBeginRegex(f),Pe=this.rules.other.htmlBeginRegex(f),ye=this.rules.other.blockquoteBeginRegex(f);for(;e;){let K=e.split(`
191
- `,1)[0],H;if(g=K,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),H=g):H=g.replace(this.rules.other.leadingSpaceTab,Se=>Se.replace(this.rules.other.tabCharGlobal," ")),Z.test(g)||le.test(g)||Pe.test(g)||ye.test(g)||M.test(g)||v.test(g))break;if(H.search(this.rules.other.nonSpaceChar)>=f||!g.trim())c2+=`
192
- `+H.slice(f);else{if(w||b.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Z.test(b)||le.test(b)||v.test(b))break;c2+=`
193
- `+g}w=!g.trim(),p+=K+`
194
- `,e=e.substring(K.length+1),b=H.slice(f)}}r.loose||(i?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(i=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c2),loose:!1,text:c2,tokens:[]}),r.raw+=p}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items)if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),!r.loose){let p=a.tokens.filter(d=>d.type==="space"),
195
- c2=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));r.loose=c2}for(let a of r.items){let p=a.tokens[0];if(a.task&&(p?.type==="text"||p?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.
196
- inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let c2=this.rules.other.listTaskCheckbox.exec(a.raw);if(c2){let d={type:"checkbox",raw:c2[0]+" ",checked:c2[0]!=="[ ]"};a.checked=d.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):
197
- a.tokens.unshift(d)}}else a.task&&(a.task=!1)}if(r.loose)for(let a of r.items){a.loose=!0;for(let p of a.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ie(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&oe(t[2],"()")!==-1)return;let n=q(t[1]).replace(this.rules.other.multipleSpaceGlobal,
198
- " "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:L(t[0],`
199
- `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=se(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
200
- `):[],o={type:"table",raw:L(t[0],`
201
- `),header:[],align:[],rows:[]};if(n.length===s.length){for(let i of s)this.rules.other.tableAlignRight.test(i)?o.align.push("right"):this.rules.other.tableAlignCenter.test(i)?o.align.push("center"):this.rules.other.tableAlignLeft.test(i)?o.align.push("left"):o.align.push(null);for(let i=0;i<n.length;i++)o.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:o.align[i]});for(let i of r)o.rows.push(se(i,o.header.length).map((u,a)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.
202
- align[a]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],`
192
+ `),R=this.list(P);o[o.length-1]=R,i=i.substring(0,i.length-g.raw.length)+R.raw,r=r.substring(0,r.length-k.raw.length)+R.raw,n=P.substring(o.at(-1).raw.length).split(`
193
+ `);continue}}return{type:"blockquote",raw:i,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=e,i=()=>n.length-e.length,r=t[1].trim(),o=r.length>1,s={type:"list",raw:"",ordered:o,start:o?+r.slice(0,-1):"",loose:!1,items:[]};r=o?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=o?r:"[*+-]");let l=this.rules.other.listItemRegex(r),u=!1;for(;e;){let p=!1,d="";if(!(t=l.exec(e))||this.rules.block.hr.test(e))break;let g=i();e=e.substring(t[0].length);let k=t[2].split(
194
+ `
195
+ `,1)[0],P=t[1].length,R=this.options.pedantic?X(k,P):k.replace(this.rules.other.leadingSpaceTab,W=>X(W,P)),m=e.split(`
196
+ `,1)[0],E=!R.trim(),b=0;if(this.options.pedantic?(b=2,d=R.trimStart()):E?b=P+1:(b=R.search(this.rules.other.nonSpaceChar),b=b>4?1:b,d=R.slice(b),b+=P),E&&this.rules.other.blankLine.test(m)&&(e=e.substring(m.length+1),p=!0),!p){let W=this.rules.other.nextBulletRegex(b),ue=this.rules.other.hrRegex(b),pe=this.rules.other.fencesBeginRegex(b),ce=this.rules.other.headingBeginRegex(b),$e=this.rules.other.htmlBeginRegex(b),Le=this.rules.other.blockquoteBeginRegex(b);for(;e;){let he=e.split(`
197
+ `,1)[0],G;if(m=he,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),G=m):G=m.replace(this.rules.other.leadingSpaceTab,Ae=>X(Ae)),pe.test(m)||ce.test(m)||$e.test(m)||Le.test(m)||W.test(m)||ue.test(m))break;if(G.search(this.rules.other.nonSpaceChar)>=b||!m.trim())d+=`
198
+ `+G.slice(b);else{if(E||R.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||pe.test(R)||ce.test(R)||ue.test(R))break;d+=`
199
+ `+m}E=!m.trim(),e=e.substring(he.length+1),R=G.slice(b)}}let H=n.slice(g,i());s.loose||(u?s.loose=!0:this.rules.other.doubleBlankLine.test(H)&&(u=!0)),s.items.push({type:"list_item",raw:H,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]})}let c2=s.items.at(-1);if(c2)c2.raw=c2.raw.trimEnd(),c2.text=c2.text.trimEnd();else return;s.raw=n.slice(0,i()).trimEnd();for(let p of s.items)if(this.lexer.state.top=!1,p.tokens=this.lexer.blockTokens(p.text,[]),!s.loose){let d=p.
200
+ tokens.filter(k=>k.type==="space"),g=d.length>0&&d.some(k=>this.rules.other.anyLine.test(k.raw));s.loose=g}for(let p of s.items){let d=p.tokens[0];if(p.task&&(d?.type==="text"||d?.type==="paragraph")){p.text=p.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let k=this.lexer.inlineQueue.length-1;k>=0;k--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)){this.
201
+ lexer.inlineQueue[k].src=this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask,"");break}let g=this.rules.other.listTaskCheckbox.exec(p.raw);if(g){let k={type:"checkbox",raw:g[0]+" ",checked:g[0]!=="[ ]"};p.checked=k.checked,s.loose?p.tokens[0]&&["paragraph","text"].includes(p.tokens[0].type)&&"tokens"in p.tokens[0]&&p.tokens[0].tokens?(p.tokens[0].raw=k.raw+p.tokens[0].raw,p.tokens[0].text=k.raw+p.tokens[0].text,p.tokens[0].tokens.unshift(k)):p.tokens.unshift({type:"paragraph",
202
+ raw:k.raw,text:k.raw,tokens:[k]}):p.tokens.unshift(k)}}else p.task&&(p.task=!1)}if(s.loose)for(let p of s.items){p.loose=!0;for(let d of p.tokens)d.type==="text"&&(d.type="paragraph")}return s}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ae(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&le(t[2],"()")!==-1)return;let n=v(t[1]).replace(this.
203
+ rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:A(t[0],`
204
+ `),href:i,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=oe(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
205
+ `):[],o={type:"table",raw:A(t[0],`
206
+ `),header:[],align:[],rows:[]};if(n.length===i.length){for(let s of i)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of r)o.rows.push(oe(s,o.header.length).map((l,u)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:o.
207
+ align[u]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:A(t[0],`
203
208
  `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
204
209
  `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.
205
210
  test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)==="!"?2:1;if(!this.
206
- options.pedantic&&we(e,t[1],n,this.rules))return;let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let i=L(s.slice(0,-1),"\\");if((s.length-i.length)%2===0)return}else{let i=oe(t[2],"()");if(i===-2)return;if(i>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.
207
- exec(r);i&&(r=i[1],o=i[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),Oe(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)==="!"?2:1;if(!this.
208
- options.pedantic&&we(e,n[1],s,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[q(r)];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Oe(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...s[0]].length-1,i,u,a=o,p=0,c2=s[0][0],d=n===
209
- c2,m=c2==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,t=t.slice(-1*e.length+o);(s=m.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(u=[...i].length,s[3]||s[4]){a+=u;continue}else if(s[5]||s[6]){if(o%3&&!((o+u)%3)){p+=u;continue}if(d)break}if(a-=u,a>0)continue;u=Math.min(u,u+a+p);let b=[...s[0]][0].length,g=e.slice(0,o+s.index+b+u);if(Math.min(o,u)%2){let f=g.slice(1,-1);return{type:"em",raw:g,text:f,tokens:this.lexer.inlineTokens(
210
- f)}}let w=g.slice(2,-2);return{type:"strong",raw:g,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){
211
- let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...s[0]].length-1,i,u,a=o,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(u=[...i].length,u!==o))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let c2=[...s[0]][0].length,d=e.slice(0,o+s.index+c2+u),m=d.slice(o,-o);return{type:"del",raw:d,text:m,tokens:this.lexer.inlineTokens(
212
- m)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[
213
- {type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:n?t[0]:Te(t[0]),escaped:n}}}},R=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||P,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.
214
- state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:x,block:j.normal,inline:D.normal};this.options.pedantic?(t.block=j.pedantic,t.inline=D.pedantic):this.options.gfm&&(t.block=j.gfm,this.options.breaks?t.inline=D.breaks:t.inline=D.gfm),this.tokenizer.rules=t}static get rules(){return{block:j,inline:D}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(x.carriageReturn,`
215
- `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(x.tabCharGlobal," ").replace(x.spaceLine,""));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(i=>(r=i.call({lexer:this},e,t))?(e=e.substring(
216
- r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let i=t.at(-1);r.raw.length===1&&i!==void 0?i.raw+=`
217
- `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(`
211
+ options.pedantic&&_e(e,t[1],n,this.rules))return;let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let s=A(i.slice(0,-1),"\\");if((i.length-s.length)%2===0)return}else{let s=le(t[2],"()");if(s===-2)return;if(s>-1){let u=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,u).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.
212
+ exec(r);s&&(r=s[1],o=s[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?r=r.slice(1):r=r.slice(1,-1)),Se(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let i=n[0].charAt(0)==="!"?2:1;if(!this.
213
+ options.pedantic&&_e(e,n[1],i,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[v(r)];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Se(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...i[0]].length-1,s,l,u=o,c2=0,p=i[0][0],d=n===
214
+ p,g=p==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(g.lastIndex=0,t=t.slice(-1*e.length+o);(i=g.exec(t))!==null;){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s)continue;if(l=[...s].length,i[3]||i[4]){u+=l;continue}else if(i[5]||i[6]){if(o%3&&!((o+l)%3)){c2+=l;continue}if(d)break}if(u-=l,u>0)continue;l=Math.min(l,l+u+c2);let k=[...i[0]][0].length,P=e.slice(0,o+i.index+k+l);if(Math.min(o,l)%2){let m=P.slice(1,-1);return{type:"em",raw:P,text:m,tokens:this.lexer.inlineTokens(
215
+ m)}}let R=P.slice(2,-2);return{type:"strong",raw:P,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){
216
+ let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...i[0]].length-1,s,l,u=o,c2=this.rules.inline.delRDelim;for(c2.lastIndex=0,t=t.slice(-1*e.length+o);(i=c2.exec(t))!==null;){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s||(l=[...s].length,l!==o))continue;if(i[3]||i[4]){u+=l;continue}if(u-=l,u>0)continue;l=Math.min(l,l+u);let p=[...i[0]][0].length,d=e.slice(0,o+i.index+p+l),g=d.slice(o,-o);return{type:"del",raw:d,text:g,tokens:this.lexer.inlineTokens(
217
+ g)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,i;if(t[2]==="@")n=t[0],i="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:n,href:i,autolink:!0,tokens:[
218
+ {type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:n?t[0]:ye(t[0]),escaped:n}}}},T=class a{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||y,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.
219
+ state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:x,block:F.normal,inline:Z.normal};this.options.pedantic?(t.block=F.pedantic,t.inline=Z.pedantic):this.options.gfm&&(t.block=F.gfm,this.options.breaks?t.inline=Z.breaks:t.inline=Z.gfm),this.tokenizer.rules=t}static get rules(){return{block:F,inline:Z}}static lex(e,t){return new a(t).lex(e)}static lexInline(e,t){return new a(t).inlineTokens(e)}lex(e){e=e.replace(x.carriageReturn,`
220
+ `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(x.tabCharGlobal," ").replace(x.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(s=>(r=s.call({lexer:this},e,t))?(e=e.substring(
221
+ r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=`
222
+ `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
218
223
  `)?"":`
219
- `)+r.raw,i.text+=`
220
- `+r.text,this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.
221
- length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(`
224
+ `)+r.raw,s.text+=`
225
+ `+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.
226
+ length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
222
227
  `)?"":`
223
- `)+r.raw,i.text+=`
224
- `+r.raw,this.inlineQueue.at(-1).src=i.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let i=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(p=>{a=p.call({lexer:this},u),typeof a=="number"&&a>=0&&(i=Math.min(i,a))}),i<1/0&&i>=
225
- 0&&(o=e.substring(0,i+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let i=t.at(-1);n&&i?.type==="paragraph"?(i.raw+=(i.raw.endsWith(`
228
+ `)+r.raw,s.text+=`
229
+ `+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let s=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(c2=>{u=c2.call({lexer:this},l),typeof u=="number"&&u>=0&&(s=Math.min(s,u))}),s<1/0&&
230
+ s>=0&&(o=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
226
231
  `)?"":`
227
- `)+r.raw,i.text+=`
228
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="text"?(i.raw+=(i.raw.endsWith(`
232
+ `)+r.raw,s.text+=`
233
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
229
234
  `)?"":`
230
- `)+r.raw,i.text+=`
231
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=n[0],
232
- r=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,q(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(")");try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e;if(this.tokens.links&&e.includes("[")){let i=this.tokenizer.rules.inline.reflinkSearch,u=a=>{let p=a.lastIndexOf("[");if(!Object.hasOwn(
233
- this.tokens.links,q(a.slice(p+1,-1))))return a;if(p>1&&a.charAt(0)!=="!"){let c2=a.slice(1,p-1);if(this.linkInText(c2))return"["+c2.replace(i,u)+"]["+"a".repeat(a.length-p-2)+"]"}return"["+"a".repeat(a.length-2)+"]"};n=n.replace(i,u)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,i=>"+".repeat(i.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(i,u,a)=>{let p=a?a.length:0;return i.slice(0,p)+"["+"a".repeat(i.length-p-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},
234
- n)??n;let s=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(r=""),s=!1;let i;if(this.options.extensions?.inline?.some(a=>(i=a.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.
235
- tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let a=t.at(-1);i.type==="text"&&a?.type==="text"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.
236
- autolink(e)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),t.push(i);continue}let u=e;if(this.options.extensions?.startInline){let a=1/0,p=e.slice(1),c2;this.options.extensions.startInline.forEach(d=>{c2=d.call({lexer:this},p),typeof c2=="number"&&c2>=0&&(a=Math.min(a,c2))}),a<1/0&&a>=0&&(u=e.substring(0,a+1))}if(i=this.tokenizer.inlineText(u)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(r=i.raw.slice(-1)),s=!0;
237
- let a=t.at(-1);a?.type==="text"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},S=class{options;parser;constructor(e){this.options=e||P}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(x.notSpaceStart)?.[0],r=e?e.replace(x.endingNewline,"")+`
238
- `:"";return s?'<pre><code class="language-'+O(s)+'">'+(n?r:O(r,!0))+`</code></pre>
239
- `:"<pre><code>"+(n?r:O(r,!0))+`</code></pre>
235
+ `)+r.raw,s.text+=`
236
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],
237
+ r=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,v(i.slice(r+1,-1))))&&!(r>1&&this.linkInText(i.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(")");try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e;if(this.tokens.links&&e.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,l=u=>{let c2=u.lastIndexOf("[");if(!Object.hasOwn(
238
+ this.tokens.links,v(u.slice(c2+1,-1))))return u;if(c2>1&&u.charAt(0)!=="!"){let p=u.slice(1,c2-1);if(this.linkInText(p))return"["+p.replace(s,l)+"]["+"a".repeat(u.length-c2-2)+"]"}return"["+"a".repeat(u.length-2)+"]"};n=n.replace(s,l)}n=n.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(s,l,u)=>u?"+".repeat(s.length):l?l+s.slice(l.length,-l.length).replace(/`/g,"+")+l:s),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,l,u)=>{let c2=u?u.length:0;return s.slice(0,c2)+"["+"a".repeat(
239
+ s.length-c2-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(r=""),i=!1;let s;if(this.options.extensions?.inline?.some(u=>(s=u.call({lexer:this},e,t))?(e=e.substring(s.raw.length),t.push(s),!0):!1))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.
240
+ link(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(s.raw.length);let u=t.at(-1);s.type==="text"&&u?.type==="text"?(u.raw+=s.raw,u.text+=s.text):t.push(s);continue}if(s=this.tokenizer.emStrong(e,n,r)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.del(e,n,r)){
241
+ e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),t.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),t.push(s);continue}let l=e;if(this.options.extensions?.startInline){let u=1/0,c2=e.slice(1),p;this.options.extensions.startInline.forEach(d=>{p=d.call({lexer:this},c2),typeof p=="number"&&p>=0&&(u=Math.min(u,p))}),u<1/0&&u>=0&&(l=e.substring(0,u+1))}if(s=this.tokenizer.inlineText(l)){e=e.substring(
242
+ s.raw.length),s.raw.slice(-1)!=="_"&&(r=s.raw.slice(-1)),i=!0;let u=t.at(-1);u?.type==="text"?(u.raw+=s.raw,u.text+=s.text):t.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},$=class{options;parser;constructor(e){this.options=e||y}space(e){return""}code({text:e,lang:t,escaped:n}){let i=(t||"").match(x.notSpaceStart)?.[0],r=e?e.replace(x.endingNewline,
243
+ "")+`
244
+ `:"";return i?'<pre><code class="language-'+w(i)+'">'+(n?r:w(r,!0))+`</code></pre>
245
+ `:"<pre><code>"+(n?r:w(r,!0))+`</code></pre>
240
246
  `}blockquote({tokens:e}){return`<blockquote>
241
247
  ${this.parser.parse(e)}</blockquote>
242
248
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
243
249
  `}hr(e){return`<hr>
244
- `}list(e){let t=e.ordered,n=e.start,s="";for(let i=0;i<e.items.length;i++){let u=e.items[i];s+=this.listitem(u)}let r=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+r+o+`>
245
- `+s+"</"+r+`>
250
+ `}list(e){let t=e.ordered,n=e.start,i="";for(let s=0;s<e.items.length;s++){let l=e.items[s];i+=this.listitem(l)}let r=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+r+o+`>
251
+ `+i+"</"+r+`>
246
252
  `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
247
253
  `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
248
- `}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];n="";for(let i=0;i<o.length;i++)n+=this.tablecell(o[i]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
254
+ `}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let i="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];n="";for(let s=0;s<o.length;s++)n+=this.tablecell(o[s]);i+=this.tablerow({text:n})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
249
255
  <thead>
250
256
  `+t+`</thead>
251
- `+s+`</table>
257
+ `+i+`</table>
252
258
  `}tablerow({text:e}){return`<tr>
253
259
  ${e}</tr>
254
260
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
255
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${O(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:s,autolink:r}){let o=r?O(n,!0):this.parser.parseInline(s),i=re(e);if(i===null)return o;e=O(i,r);let u='<a href="'+e+'"';return t&&(u+=' title="'+O(t)+'"'),u+=">"+o+"</a>",u}image({href:e,title:t,
256
- text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=re(e);if(r===null)return O(n);e=r;let o=`<img src="${O(e)}" alt="${O(n)}"`;return t&&(o+=` title="${O(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:O(e.text)}},z=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({
257
- text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},T=class l2{options;renderer;textRenderer;constructor(e){this.options=e||P,this.options.renderer=this.options.renderer||new S,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new z}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.
258
- options.extensions?.renderers?.[s.type]){let o=s,i=this.options.extensions.renderers[o.type].call({parser:this},o);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=i||"";continue}}let r=s;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(
261
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${w(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:i,autolink:r}){let o=r?w(n,!0):this.parser.parseInline(i),s=ie(e);if(s===null)return o;e=w(s,r);let l='<a href="'+e+'"';return t&&(l+=' title="'+w(t)+'"'),l+=">"+o+"</a>",l}image({href:e,title:t,
262
+ text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let r=ie(e);if(r===null)return w(n);e=r;let o=`<img src="${w(e)}" alt="${w(n)}"`;return t&&(o+=` title="${w(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:w(e.text)}},z=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({
263
+ text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},O=class a2{options;renderer;textRenderer;constructor(e){this.options=e||y,this.options.renderer=this.options.renderer||new $,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new z}static parse(e,t){return new a2(t).parse(e)}static parseInline(e,t){return new a2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let i=e[n];if(this.
264
+ options.extensions?.renderers?.[i.type]){let o=i,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=s||"";continue}}let r=i;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(
259
265
  r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return t}parseInline(e,t=this.
260
- renderer){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let i=this.options.extensions.renderers[r.type].call({parser:this},r);if(i!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=i||"";continue}}let o=r;switch(o.type){case"escape":{n+=t.text(o);break}case"html":{n+=t.html(o);break}case"link":{n+=t.link(o);break}case"image":{n+=t.image(o);break}case"check\
261
- box":{n+=t.checkbox(o);break}case"strong":{n+=t.strong(o);break}case"em":{n+=t.em(o);break}case"codespan":{n+=t.codespan(o);break}case"br":{n+=t.br(o);break}case"del":{n+=t.del(o);break}case"text":{n+=t.text(o);break}default:{let i='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}},_=class{options;block;constructor(e){this.options=e||P}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStr\
262
- ongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?R.lex:R.lexInline}provideParser(e=this.block){return e?T.parse:T.parseInline}},F=class{defaults=I();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=T;Renderer=S;TextRenderer=z;Lexer=R;Tokenizer=y;Hooks=_;constructor(...e){
263
- this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)n=n.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let i of o)n=n.concat(this.walkTokens(i.tokens,t));break}case"list":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let i=r[o].flat(1/0);n=n.concat(this.walkTokens(i,t))}):
264
- r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...i){let u=r.renderer.apply(this,i);return u===!1&&(u=o.apply(this,i)),u}:t.renderers[r.name]=r.renderer}if("tokenize\
265
- r"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||
266
- new S(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let i=o,u=n.renderer[i],a=r[i];r[i]=(...p)=>{let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new y(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let i=o,u=n.tokenizer[i],
267
- a=r[i];r[i]=(...p)=>{let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new _;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let i=o,u=n.hooks[i],a=r[i];_.passThroughHooks.has(o)?r[i]=p=>{if(this.defaults.async&&_.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await u.call(r,p);return a.call(r,d)})();let c2=u.call(r,p);return a.call(r,c2)}:r[i]=(...p)=>{
268
- if(this.defaults.async)return(async()=>{let d=await u.apply(r,p);return d===!1&&(d=await a.apply(r,p)),d})();let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let u=[];return u.push(o.call(this,i)),r&&(u=u.concat(r.call(this,i))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return R.lex(e,t??this.defaults)}parser(e,t){
269
- return T.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input paramete\
270
- r is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let u=o.hooks?await o.hooks.preprocess(n):n,p=await(o.hooks?await o.hooks.provideLexer(e):e?R.lex:R.lexInline)(u,o),c2=o.hooks?await o.hooks.processAllTokens(p):p;o.walkTokens&&await Promise.all(this.walkTokens(c2,o.walkTokens));let m=await(o.hooks?await o.hooks.provideParser(e):e?T.parse:T.parseInline)(c2,o);return o.hooks?await o.hooks.postprocess(m):m})().
271
- catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let a=(o.hooks?o.hooks.provideLexer(e):e?R.lex:R.lexInline)(n,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let c2=(o.hooks?o.hooks.provideParser(e):e?T.parse:T.parseInline)(a,o);return o.hooks&&(c2=o.hooks.postprocess(c2)),c2}catch(u){return i(u)}}}onError(e,t){return n=>{if(n.message+=`
272
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+O(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},E=new F;function k(l3,e){return E.parse(l3,e)}k.options=k.setOptions=function(l3){return E.setOptions(l3),k.defaults=E.defaults,W(k.defaults),k};k.getDefaults=I;k.defaults=P;function yt(...l3){return E.use(...l3),k.defaults=E.defaults,W(k.defaults),k}k.use=yt;k.walkTokens=function(l3,e){return E.walkTokens(
273
- l3,e)};k.parseInline=E.parseInline;k.Parser=T;k.parser=T.parse;k.Renderer=S;k.TextRenderer=z;k.Lexer=R;k.lexer=R.lex;k.Tokenizer=y;k.Hooks=_;k.parse=k;var gn=k.options,fn=k.setOptions,mn=k.walkTokens,xn=k.parseInline;var Rn=T.parse,Tn=R.lex;import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir}from"os";import{basename,dirname,join}from"path";function fuzzyMatch(query,text){let queryLower=query.toLowerCase(),textLower=text.toLowerCase(),matchQuery=normalizedQuery=>{if(normalizedQuery.length===0)return{matches:!0,score:0};if(normalizedQuery.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(;queryIndex<normalizedQuery.length;){let i=textLower.indexOf(normalizedQuery[queryIndex],lastMatchIndex+1);if(i===-1)break;let isWordBoundary=i===0||/[\s\-_./:]/.test(textLower[i-1]);
266
+ renderer){this.renderer.parser=this;let n="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let s=this.options.extensions.renderers[r.type].call({parser:this},r);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=s||"";continue}}let o=r;switch(o.type){case"escape":{n+=t.text(o);break}case"html":{n+=t.html(o);break}case"link":{n+=t.link(o);break}case"image":{n+=t.image(o);break}case"check\
267
+ box":{n+=t.checkbox(o);break}case"strong":{n+=t.strong(o);break}case"em":{n+=t.em(o);break}case"codespan":{n+=t.codespan(o);break}case"br":{n+=t.br(o);break}case"del":{n+=t.del(o);break}case"text":{n+=t.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},L=class{options;block;constructor(e){this.options=e||y}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStr\
268
+ ongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?T.lex:T.lexInline}provideParser(e=this.block){return e?O.parse:O.parseInline}};function C(a3,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)a3.push(e[t]);else a3.push(e)}var U=class{defaults=B();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.
269
+ parseMarkdown(!1);Parser=O;Renderer=$;TextRenderer=z;Lexer=T;Tokenizer=_;Hooks=L;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let i of e)switch(C(n,t.call(this,i)),i.type){case"table":{let r=i;for(let o of r.header)C(n,this.walkTokens(o.tokens,t));for(let o of r.rows)for(let s of o)C(n,this.walkTokens(s.tokens,t));break}case"list":{let r=i;C(n,this.walkTokens(r.items,t));break}default:{let r=i;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.
270
+ type].forEach(o=>{let s=r[o].flat(1/0);C(n,this.walkTokens(s,t))}):r.tokens&&C(n,this.walkTokens(r.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...s){let l=r.renderer.apply(this,s);return l===!1&&(l=o.apply(
271
+ this,s)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),i.
272
+ extensions=t),n.renderer){let r=this.defaults.renderer||new $(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,l=n.renderer[s],u=r[s];r[s]=(...c2)=>{let p=l.apply(r,c2);return p===!1&&(p=u.apply(r,c2)),p||""}}i.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new _(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options",
273
+ "rules","lexer"].includes(o))continue;let s=o,l=n.tokenizer[s],u=r[s];r[s]=(...c2)=>{let p=l.apply(r,c2);return p===!1&&(p=u.apply(r,c2)),p}}i.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new L;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,l=n.hooks[s],u=r[s];L.passThroughHooks.has(o)?r[s]=c2=>{if(this.defaults.async&&L.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await l.call(r,c2);return u.
274
+ call(r,d)})();let p=l.call(r,c2);return u.call(r,p)}:r[s]=(...c2)=>{if(this.defaults.async)return(async()=>{let d=await l.apply(r,c2);return d===!1&&(d=await u.apply(r,c2)),d})();let p=l.apply(r,c2);return p===!1&&(p=u.apply(r,c2)),p}}i.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(s){let l=[];return l.push(o.call(this,s)),r&&C(l,r.call(this,s)),l}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},
275
+ this}lexer(e,t){return T.lex(e,t??this.defaults)}parser(e,t){return O.parse(e,t??this.defaults)}parseMarkdown(e){return(n,i)=>{let r={...i},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof n!=
276
+ "string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let l=o.hooks?await o.hooks.preprocess(n):n,c2=await(o.hooks?await o.hooks.provideLexer(e):e?T.lex:T.lexInline)(l,o),p=o.hooks?await o.hooks.processAllTokens(c2):c2;o.walkTokens&&await Promise.all(this.walkTokens(p,o.walkTokens));let g=await(o.hooks?await o.hooks.provideParser(e):e?O.parse:O.parseInline)(
277
+ p,o);return o.hooks?await o.hooks.postprocess(g):g})().catch(s);try{o.hooks&&(n=o.hooks.preprocess(n));let u=(o.hooks?o.hooks.provideLexer(e):e?T.lex:T.lexInline)(n,o);o.hooks&&(u=o.hooks.processAllTokens(u)),o.walkTokens&&this.walkTokens(u,o.walkTokens);let p=(o.hooks?o.hooks.provideParser(e):e?O.parse:O.parseInline)(u,o);return o.hooks&&(p=o.hooks.postprocess(p)),p}catch(l){return s(l)}}}onError(e,t){return n=>{if(n.message+=`
278
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+w(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},I=new U;function f(a3,e){return I.parse(a3,e)}f.options=f.setOptions=function(a3){return I.setOptions(a3),f.defaults=I.defaults,V(f.defaults),f};f.getDefaults=B;f.defaults=y;function At(...a3){return I.use(...a3),f.defaults=I.defaults,V(f.defaults),f}f.use=At;f.walkTokens=function(a3,e){return I.walkTokens(
279
+ a3,e)};f.parseInline=I.parseInline;f.Parser=O;f.parser=O.parse;f.Renderer=$;f.TextRenderer=z;f.Lexer=T;f.lexer=T.lex;f.Tokenizer=_;f.Hooks=L;f.parse=f;var Rn=f.options,Tn=f.setOptions,On=f.walkTokens,wn=f.parseInline;var yn=O.parse,Sn=T.lex;import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir}from"os";import{basename,dirname,join}from"path";function fuzzyMatch(query,text){let queryLower=query.toLowerCase(),textLower=text.toLowerCase(),matchQuery=normalizedQuery=>{if(normalizedQuery.length===0)return{matches:!0,score:0};if(normalizedQuery.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(;queryIndex<normalizedQuery.length;){let i=textLower.indexOf(normalizedQuery[queryIndex],lastMatchIndex+1);if(i===-1)break;let isWordBoundary=i===0||/[\s\-_./:]/.test(textLower[i-1]);
274
280
  lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),isWordBoundary&&(score-=10),score+=i*.1,lastMatchIndex=i,queryIndex++}return queryIndex<normalizedQuery.length?{matches:!1,score:0}:(normalizedQuery===textLower&&(score-=100),{matches:!0,score})},primaryMatch=matchQuery(queryLower);if(primaryMatch.matches)return primaryMatch;let alphaNumericMatch=queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),
275
281
  numericAlphaMatch=queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),swappedQuery=alphaNumericMatch?`${alphaNumericMatch.groups?.digits??""}${alphaNumericMatch.groups?.letters??""}`:numericAlphaMatch?`${numericAlphaMatch.groups?.letters??""}${numericAlphaMatch.groups?.digits??""}`:"";if(!swappedQuery)return primaryMatch;let swappedMatch=matchQuery(swappedQuery);return swappedMatch.matches?{matches:!0,score:swappedMatch.score+5}:primaryMatch}function fuzzyFilter(items,query,getText){if(!query.
276
- trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a,b)=>a.totalScore-b.totalScore),results.map(r=>r.item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.
282
+ trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a3,b)=>a3.totalScore-b.totalScore),results.map(r=>r.item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.
277
283
  replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",segments=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment));if(segments.length===0)return normalized;let pattern=segments.join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&
278
284
  (lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-
279
285
  1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.
@@ -296,51 +302,56 @@ try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{bas
296
302
  this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname(
297
303
  expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}
298
304
  let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname(homeRelativeDir);relativePath=`~/${dir==="."?name:join(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join(
299
- dirname(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a,b)=>{let aIsDir=a.label.endsWith(
300
- "/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){
301
- return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options.
302
- signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b)=>{let scoreDiff=b.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split(
303
- "/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,
304
- pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.
305
+ dirname(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a3,b)=>{let aIsDir=a3.label.endsWith(
306
+ "/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a3.label.localeCompare(b.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){
307
+ return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,[baseDirEntries,recursiveEntries]=await Promise.all([this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,
308
+ options.signal)]),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a3,b)=>{let scoreDiff=b.score-a3.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(
309
+ a3.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a3.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a3.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.
310
+ displayBase,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.
305
311
  trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";var generation=0;function renderedMarkdownGeneration(){return generation}function invalidateRenderedMarkdown(){generation++}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;
306
312
  function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.
307
313
  slice(4,8)),b2=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b2!==void 0?{r:r2,g:g2,b:b2}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b!==void 0?{r,g,b}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)
308
- return match[1]==="2"?"light":"dark"}import{execSync}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,capabilityOverrides={},cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}function probeTmuxHyperlinks(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe",
309
- "ignore"]}).split(",").map(feature=>feature.trim()).includes("hyperlinks")}catch{return!1}}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="\
310
- win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:null,trueColor:hasTrueColorHint,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:
311
- process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:
312
- terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(
313
- hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=(process.env.HUMAIN_TERMINAL_IMAGE_PROTOCOL??process.env.PI_IMAGE_PROTOCOL)?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_TRUE_COLOR??process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==
314
- void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?void 0:()=>hyperlinks),...capabilityOverrides}}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null}function setCapabilityOverrides(overrides){capabilityOverrides.images===
315
- overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null)}function setCapabilities(caps){cachedCapabilities=caps}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(
316
- Math.random()*4294967294)+1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+
317
- 4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`in\
318
- line=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;
319
- function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];
320
- return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){
321
- return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(controls===
322
- void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match[1]);if(!metadata)return;let commandStart=match.index,commandControls=match[1],transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===
323
- -1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match[1].split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.
324
- imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match[1],metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=/\x1b_G([^;]*);/.exec(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=
325
- metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match[1].split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,
326
- `r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match[0].length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={
327
- widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*
328
- scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*
329
- imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;
330
- let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+
331
- 7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}
332
- function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.slice(12,16).toString("ascii");if(chunk==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<
333
- 25)return null;let bits=buffer.readUInt32LE(21),width=(bits&16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(
334
- base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,
335
- columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){
336
- return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.
337
- push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`),`[Image: ${parts.join(" ")}]`}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){
314
+ return match[1]==="2"?"light":"dark"}import{execFile}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,capabilityOverrides={},capabilityChangeListeners=new Set,cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}var tmuxHyperlinks,tmuxProbeStarted=!1;function probeTmuxHyperlinks(){return tmuxHyperlinks!==
315
+ void 0?tmuxHyperlinks:(tmuxProbeStarted||(tmuxProbeStarted=!0,startTmuxProbe()),!1)}function startTmuxProbe(){let answer=forwards=>{if(tmuxHyperlinks=forwards,!(!forwards||!cachedBeforeTmuxAnswer)){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1;for(let listener of capabilityChangeListeners)listener()}};try{let child=execFile("tmux",["display-message","-p","#{client_termfeatures}"],{encoding:"utf8"},(error,stdout)=>{clearTimeout(timeout),answer(!error&&stdout.split(",").map(feature=>feature.trim()).
316
+ includes("hyperlinks"))}),timeout=setTimeout(()=>child.kill(),250);timeout.unref(),child.unref(),child.stdin?.end(),child.stdout?.unref(),child.stderr?.unref()}catch{answer(!1)}}function onCapabilitiesChange(listener){return capabilityChangeListeners.add(listener),()=>capabilityChangeListeners.delete(listener)}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||
317
+ "",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:
318
+ process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram===
319
+ "iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value===
320
+ "0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=(process.env.HUMAIN_TERMINAL_IMAGE_PROTOCOL??process.env.PI_IMAGE_PROTOCOL)?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol===
321
+ "0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_TRUE_COLOR??process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks,probePending=!1;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?()=>{let forwards=probeTmuxHyperlinks();return probePending=tmuxHyperlinks===
322
+ void 0,forwards}:()=>hyperlinks),...capabilityOverrides},cachedBeforeTmuxAnswer=probePending}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,tmuxHyperlinks=void 0,tmuxProbeStarted=!1}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&
323
+ capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null,cachedBeforeTmuxAnswer=!1)}function setCapabilities(caps){cachedCapabilities=caps,cachedBeforeTmuxAnswer=!1}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+
324
+ 1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.
325
+ length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==
326
+ !1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){
327
+ if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.
328
+ get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??
329
+ fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(
330
+ controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match[1]);if(!metadata)return;let commandStart=match.index,commandControls=match[1],transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.
331
+ test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match[1].split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,
332
+ transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match[1],metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=/\x1b_G([^;]*);/.exec(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.
333
+ min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match[1].split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.
334
+ join(",")};${line.slice(match.index+match[0].length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.
335
+ max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(
336
+ scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);
337
+ columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.
338
+ readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;
339
+ let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.
340
+ from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.slice(12,16).toString("ascii");if(chunk==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<25)return null;let bits=buffer.readUInt32LE(21),width=(bits&
341
+ 16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(base64Data):mimeType==="image/gif"?getGifDimensions(
342
+ base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.
343
+ widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){
344
+ let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.
345
+ heightPx}`),`[Image: ${parts.join(" ")}]`}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){
338
346
  return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_\
339
- pi:c\x07";function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var Container=class{children=[];mouseLayout;addChild(component){this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){for(let child of this.children)child.invalidate?.()}handleMouse(event){
340
- if(event.y<0||event.y>=event.height)return;let mouseChildren=this.mouseLayout?.width===event.width?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(event.width).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}render(width){
341
- let lines=[],mouseChildren=[];for(let child of this.children){let childLines=child.render(width);mouseChildren.push({component:child,height:childLines.length});for(let line of childLines)lines.push(line)}return this.mouseLayout={width,children:mouseChildren},lines}},SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,
342
- afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+
343
- SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){
347
+ pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var stableRenders=new WeakSet;function markStableRender(componentClass){stableRenders.add(componentClass.prototype.render)}function isStableRender(component){return component instanceof Container&&component.render===Container.prototype.render||stableRenders.has(component.render)}
348
+ function renderSharedLines(component,width){return component instanceof Container&&component.render===Container.prototype.render?component.renderShared(width):component.render(width)}function renderChildren(children,width,previous){let count=children.length,before=previous?.width===width?previous:void 0,index=0,offset=0,changedLines;if(before!==void 0){for(;index<count;index++){let child=children[index],lines=renderSharedLines(child,width);if(index>=before.children.length||before.children[index]!==
349
+ child||!sameLines(child,lines,before,index,offset)){changedLines=lines;break}offset+=lines.length}if(index===count&&count===before.children.length)return before}let arrays=new Array(count),heights=new Array(count);for(let i=0;i<index;i++)arrays[i]=before.arrays[i],heights[i]=before.heights[i];let joined=before!==void 0&&offset>0?before.lines.slice(0,offset):[];for(;index<count;index++){let lines=changedLines??renderSharedLines(children[index],width);changedLines=void 0,arrays[index]=lines,heights[index]=
350
+ lines.length;for(let i=0;i<lines.length;i++)joined.push(lines[i])}return{width,children:children.slice(),arrays,heights,lines:joined}}function sameLines(child,lines,previous,index,offset){if(lines===previous.arrays[index]&&isStableRender(child))return!0;let height=previous.heights[index];if(lines.length!==height)return!1;let joined=previous.lines;for(let i=0;i<height;i++)if(lines[i]!==joined[offset+i])return!1;return!0}var Container=class{children=[];rendered;addChild(component){this.children.push(
351
+ component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){this.rendered=void 0;for(let child of this.children)child.invalidate?.()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let rendered=this.rendered?.width===event.width?this.rendered:void 0,children=rendered?.children??this.children,childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?rendered.
352
+ heights[i]:child.render(event.width).length;if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}renderShared(width){return this.rendered=renderChildren(this.children,width,this.rendered),this.rendered.lines}render(width){return this.renderShared(width).slice()}},SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){
353
+ if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.
354
+ max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){
344
355
  return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){
345
356
  this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?
346
357
  this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):
@@ -373,19 +384,20 @@ min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);ma
373
384
  "center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.
374
385
  anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bott\
375
386
  om-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor((availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){
376
- if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a,b)=>a.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=component.render(width);maxHeight!==
377
- void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,overlayLines})=>({entry,row,col,width:w,height:overlayLines.length}));let workingHeight=Math.max(
378
- result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w?sliceByColumn(overlayLines[i],0,w,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w,termWidth)}}return result}applyLineResets(lines){
379
- let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];isImageLine(line)||(lines[i]=normalizeTerminalOutput(line)+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==
380
- -1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{row,col}}}return null}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.
381
- push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn}setPaddingX(paddingX){this.paddingX=paddingX,this.
382
- invalidateCache()}invalidateCache(){this.cache=void 0}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;
383
- if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.
384
- children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))
385
- return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(leftPad+line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(paddingX){this.paddingX=paddingX,this.
387
+ if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a3,b)=>a3.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.
388
+ render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w:w2,overlayLines})=>({entry,row,col,width:w2,height:overlayLines.length}));
389
+ let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w:w2}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w2?sliceByColumn(overlayLines[i],0,w2,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w2,
390
+ termWidth)}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];isImageLine(line)||(lines[i]=normalizeTerminalOutput(line)+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],
391
+ markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({
392
+ timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var Box=class{children=[];paddingX;paddingY;bgFn;cache;rendered;emptyLines=[];constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn}setPaddingX(paddingX){this.paddingX!==
393
+ paddingX&&(this.paddingX=paddingX,this.invalidateCache())}invalidateCache(){this.cache=void 0,this.rendered=void 0}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let rendered=this.rendered?.width===contentWidth?this.rendered:void 0,children=rendered?.children??this.
394
+ children,childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?rendered.heights[i]:child.render(contentWidth).length;if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return this.emptyLines;let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),rendered=renderChildren(
395
+ this.children,contentWidth,this.rendered);this.rendered=rendered;let childLines=rendered.lines;if(childLines.length===0)return this.emptyLines;let bgSample=this.bgFn?this.bgFn("test"):void 0,cache=this.cache&&this.cache.width===width&&this.cache.bgSample===bgSample?this.cache:void 0;if(cache?.childLines===childLines)return cache.lines;let result=[],reused=cache!==void 0&&cache.childLines.length===childLines.length;for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[i]:this.applyBg("",width));
396
+ for(let i=0;i<childLines.length;i++){let line=childLines[i];cache!==void 0&&i<cache.childLines.length&&cache.childLines[i]===line?result.push(cache.lines[this.paddingY+i]):(reused=!1,result.push(this.applyBg(leftPad+line,width)))}for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[cache.lines.length-this.paddingY+i]:this.applyBg("",width));return reused?(cache.childLines=childLines,cache.lines):(flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result)}applyBg(line,width){
397
+ let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?this.bgFn(padded):padded}};markStableRender(Box);var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(paddingX){this.paddingX=paddingX,this.
386
398
  invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-
387
399
  paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".
388
- repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,
400
+ repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};markStableRender(Text);var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,
389
401
  this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.
390
402
  intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs))}getRenderedIndicator(){let frame=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(){let renderedFrame=this.getRenderedIndicator(),
391
403
  indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}};var CancellableLoader=class extends Loader{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var KillRing=class{ring=[];push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{stack=[];push(state){this.stack.push(structuredClone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var wordSegmenter2=getWordSegmenter();function findWordBackward(text,cursor,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||
@@ -414,16 +426,18 @@ map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`
414
426
  max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-
415
427
  visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=buildDebouncePattern(
416
428
  this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new KillRing;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new UndoStack;onSubmit;onChange;disableSubmit=!1;constructor(tui,theme2,options={}){
417
- this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){
418
- return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){
419
- this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(
420
- visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.
421
- historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
429
+ this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}wrapCache={width:-1,pasteIds:"",lines:[]};wrapCacheFor(width){let pasteIds=[...this.pastes.keys()].join(","),cache=this.wrapCache;return cache.width!==width||cache.pasteIds!==
430
+ pasteIds?this.wrapCache={width,pasteIds,lines:[]}:cache.lines.length>this.state.lines.length&&(cache.lines.length=this.state.lines.length),this.wrapCache.lines}wrapLine(cache,index,line,width){let known=cache[index];if(known!==void 0&&known.text===line)return known.chunks;let chunks=wordWrapLine(line,width,[...this.segment(line,"grapheme")]);return cache[index]={text:line,chunks},chunks}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="w\
431
+ ord"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&
432
+ (this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){
433
+ let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=
434
+ structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="\
435
+ end"){let lines=text.split(`
422
436
  `);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){
423
437
  let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),
424
438
  cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);
425
439
  this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused;for(let layoutLine of visibleLines){let displayText=layoutLine.text,lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1;if(layoutLine.hasCursor&&layoutLine.cursorPos!==void 0){let before=displayText.slice(0,layoutLine.cursorPos),after=displayText.slice(layoutLine.cursorPos),
426
- marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=[...this.segment(after,"grapheme")][0]?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=`\x1B[7m${firstGrapheme}\x1B[0m`;displayText=before+marker+cursor+restAfter}else displayText=before+marker+"\x1B[7m \x1B[0m",lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0)}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?
440
+ marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=[...this.segment(after,"grapheme")][0]?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=renderFakeCursor(firstGrapheme);displayText=before+marker+cursor+restAfter}else{let cursor=renderFakeCursor(" ");displayText=before+marker+cursor,lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0)}}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?
427
441
  rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(
428
442
  line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-
429
443
  paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)
@@ -440,9 +454,9 @@ orWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cur
440
454
  `&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||
441
455
  this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(kb.matches(data,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(kb.matches(data,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(kb.matches(data,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(kb.matches(
442
456
  data,"tui.editor.pageUp")){this.pageScroll(-1);return}if(kb.matches(data,"tui.editor.pageDown")){this.pageScroll(1);return}if(kb.matches(data,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(matchesKey(data,"shift+space")){this.insertCharacter(" ");return}let printable=decodePrintableKey(data);if(printable!==void 0){this.insertCharacter(printable);return}data.charCodeAt(0)>=32&&this.insertCharacter(data)}layoutText(contentWidth){
443
- let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(visibleWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{let chunks=wordWrapLine(line,contentWidth,
444
- [...this.segment(line,"grapheme")]);for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=cursorPos-chunk.
445
- startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos}):layoutLines.push({text:chunk.text,hasCursor:!1})}}}return layoutLines}getText(){return this.state.lines.join(`
457
+ let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;let wrapCache=this.wrapCacheFor(contentWidth);for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(visibleWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{
458
+ let chunks=this.wrapLine(wrapCache,i,line,contentWidth);for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=
459
+ cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos}):layoutLines.push({text:chunk.text,hasCursor:!1})}}}return layoutLines}getText(){return this.state.lines.join(`
446
460
  `)}expandPasteMarkers(text){let result=text;for(let[pasteId,pasteContent]of this.pastes){let markerRegex=new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");result=result.replace(markerRegex,()=>pasteContent)}return result}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
447
461
  `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text);this.getText()!==normalized&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(normalized)}insertTextAtCursor(text){text&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.
448
462
  insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
@@ -458,7 +472,7 @@ let decodedText=pastedText.replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Numbe
458
472
  this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before,this.state.lines.splice(this.state.cursorLine+1,0,after),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(data,kb){if(this.disableSubmit||!matchesKey(data,"\
459
473
  enter"))return!1;let submitKeys=kb.getKeys("tui.input.submit");if(!(submitKeys.includes("shift+enter")||submitKeys.includes("shift+return")))return!1;let currentLine=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let result=this.expandPasteMarkers(this.state.lines.join(`
460
474
  `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),graphemes=[...this.segment(
461
- beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a,b)=>a-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.
475
+ beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a3,b)=>a3-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.
462
476
  lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{let x2=Number(idGroup);return x2<=targetId?fullMatch:`[paste #${x2-1}${suffixGroup}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.
463
477
  state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(
464
478
  textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(
@@ -478,15 +492,15 @@ state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRin
478
492
  `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);
479
493
  this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[
480
494
  ...this.segment(afterCursor,"grapheme")][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.
481
- cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[];for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",
482
- lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=wordWrapLine(line,width,[...this.segment(line,"grapheme")]);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];
483
- if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.
484
- findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0];this.setCursorCol(this.
485
- state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1];this.setCursorCol(this.
486
- state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),
487
- targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.
488
- state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();
489
- let lines=text.split(`
495
+ cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[],wrapCache=this.wrapCacheFor(width);for(let i=0;i<this.state.lines.length;i++){
496
+ let line=this.state.lines[i]||"",lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=this.wrapLine(wrapCache,i,line,width);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){
497
+ let vl=visualLines[i];if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(
498
+ this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,
499
+ "grapheme")][0];this.setCursorCol(this.state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.
500
+ length-1];this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.
501
+ findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(
502
+ findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){
503
+ this.exitHistoryBrowsing();let lines=text.split(`
490
504
  `);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||
491
505
  "");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
492
506
  `);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.
@@ -517,7 +531,7 @@ map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),h
517
531
  this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),
518
532
  defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),data=this.base64Data,dimensions=this.dimensions;caps.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=toPng(this.base64Data,this.mimeType)??void 0,data=this.pngData??null,data&&(dimensions=getPngDimensions(data)??dimensions));let lines;if(caps.images&&data){caps.images==="kitty"&&this.imageId===void 0&&(this.
519
533
  imageId=allocateImageId());let result=renderImage(data,dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(
520
- this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;mask;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,
534
+ this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};markStableRender(Image);var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;mask;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,
521
535
  value.length)}setMask(mask){this.mask=mask}reset(){this.value="",this.cursor=0,this.mask=void 0,this.pasteBuffer="",this.isInPaste=!1,this.killRing=new KillRing,this.lastAction=null,this.undoStack.clear()}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(
522
536
  pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
523
537
  `){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.e\
@@ -533,9 +547,9 @@ deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=t
533
547
  length)+this.value.slice(this.cursor),this.cursor-=prevText.length,this.killRing.rotate();let text=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let snapshot=this.undoStack.pop();snapshot&&(this.value=snapshot.value,this.cursor=snapshot.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=
534
548
  null,this.cursor=findWordBackward(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=findWordForward(this.value,this.cursor))}handlePaste(pastedText){this.lastAction=null,this.pushUndo();let cleanText=pastedText.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+cleanText+this.value.slice(this.cursor),this.cursor+=cleanText.length}invalidate(){}render(width){let displayValue=this.
535
549
  mask?[...segmenter.segment(this.value)].map(()=>this.mask).join(""):this.value,displayCursor=this.mask?[...segmenter.segment(this.value.slice(0,this.cursor))].length*this.mask.length:this.cursor,availableWidth=width-visibleWidth(this.prompt);if(availableWidth<=0)return[truncateToWidth(this.prompt,width,"")];if(this.value.length===0&&this.placeholder){let placeholder=truncateToWidth(this.placeholder,availableWidth,""),atCursor2=[...segmenter.segment(placeholder)][0]?.segment??" ",afterCursor2=placeholder.
536
- slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=`\x1B[7m${this.placeholderStyle(atCursor2)}\x1B[27m`,textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=displayCursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(displayValue);if(totalWidth<availableWidth)visibleText=displayValue;else{let scrollWidth=this.
550
+ slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=renderFakeCursor(this.placeholderStyle(atCursor2)),textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=displayCursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(displayValue);if(totalWidth<availableWidth)visibleText=displayValue;else{let scrollWidth=this.
537
551
  cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(displayValue.slice(0,displayCursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(displayValue,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(displayValue,startCol,Math.max(0,cursorCol-
538
- startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=`\x1B[7m${atCursor}\x1B[27m`,textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-
552
+ startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=renderFakeCursor(atCursor),textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-
539
553
  visualLength));return[this.prompt+textWithCursor+padding]}};var SYMBOLS={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",
540
554
  Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",
541
555
  rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",
@@ -598,7 +612,7 @@ cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),columnC
598
612
  `);lines=rows.map((row,index2)=>{let left=index2===0?delimiter[0]:index2===rows.length-1?delimiter[4]:delimiter[2],right=index2===0?delimiter[1]:index2===rows.length-1?delimiter[5]:delimiter[3];return`${left} ${row} ${right}`})}if(lines.length<=1)return lines[0]??"";let index=this.layoutNodes.push({type:"matrix",lines,baseline:0})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}renderNested(source2,stackFractions=!0){let rendered=new _LatexParser(source2,this.layoutNodes,this.display&&
599
613
  stackFractions).render();return rendered===void 0?(this.supported=!1,source2):rendered}};function renderLatex(source2,options={}){let layoutNodes=[],rendered=new LatexParser(source2,layoutNodes,options.display===!0).render();if(rendered===void 0)return;if(layoutNodes.length===0)return rendered.replaceAll(PROTECTED_SPACE," ");let lines=renderLayout(rendered,layoutNodes).lines,indentation=Math.min(...lines.filter(line=>line.trim()).map(line=>line.length-line.trimStart().length));return lines.map(line=>line.
600
614
  slice(indentation).trimEnd()).join(`
601
- `).trimEnd().replaceAll(PROTECTED_SPACE," ")}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,StrictStrikethroughTokenizer=class extends y{del(src){let match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match)return;let text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}};function isEscaped(source2,index){let backslashes=0;for(let position=index-1;position>=0&&source2[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source2,closing,start){
615
+ `).trimEnd().replaceAll(PROTECTED_SPACE," ")}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,StrictStrikethroughTokenizer=class extends _{del(src){let match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match)return;let text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}};function isEscaped(source2,index){let backslashes=0;for(let position=index-1;position>=0&&source2[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source2,closing,start){
602
616
  let index=source2.indexOf(closing,start);for(;index>=0&&isEscaped(source2,index);)index=source2.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source2){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source2)}function tokenizeInlineLatex(source2){let opening="",closing="";if(source2.startsWith("$$"))opening="$$",closing="$$";else if(source2.startsWith("\\("))opening="\\(",closing="\\)";else if(source2.startsWith("\\["))opening=
603
617
  "\\[",closing="\\]";else if(source2.startsWith("$")&&!/^\$\s/.test(source2))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source2,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source2.slice(opening.length,closingIndex))||/^\d/.test(source2.slice(closingIndex+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source2.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source2.slice(closingIndex+1))||source2.slice(opening.length,
604
618
  closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source2.slice(opening.length);return opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource)?{type:"latex",raw:source2,text:pendingSource,pending:!0}:void 0}let text=source2.slice(opening.length,closingIndex);return!text||text.includes(`
@@ -607,7 +621,7 @@ exec(source2);if(pendingBracket)return{type:"latexBlock",raw:pendingBracket[0],t
607
621
  `
608
622
  `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source2){let indices=[source2.indexOf("$"),source2.indexOf("\\("),source2.indexOf("\\[")].filter(index=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(
609
623
  token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
610
- `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new F;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).length>0}function lexAddedMarkdown(previous,source2){
624
+ `).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new U;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).length>0}function lexAddedMarkdown(previous,source2){
611
625
  let last=previous.tokens.length;for(let blocks=0;blocks<2;blocks++)for(last--;last>=0&&previous.tokens[last].type==="space";)last--;if(last<=0)return;let offset=0;for(let i=0;i<last;i++)offset+=previous.tokens[i].raw.length;let added=markdownParser.lexer(JSON.parse(JSON.stringify(source2.slice(offset))));if(hasLinkDefinitions(added))return;let tokens=previous.tokens.slice(0,last),length=offset;for(let token of added)tokens.push(token),length+=token.raw.length;return length===source2.length?tokens:
612
626
  void 0}function lexMarkdown(source2,complete=!0){if(!markdownCaching){let tokens2=markdownParser.lexer(source2);return trimPartialClosingFences(tokens2),tokens2}let previous=-1;for(let i=lexedMarkdown.length-1;i>=0;i--){let entry=lexedMarkdown[i];if(entry.source===source2){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.push(entry),entry.tokens}!complete&&entry.resumable&&source2.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.
613
627
  length)&&source2.startsWith(entry.source)&&(previous=i)}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source2):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=markdownParser.lexer(source2);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source2.length}return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lexedMarkdown.push({source:source2,tokens,resumable,pieced}),lexedMarkdown.
@@ -641,14 +655,15 @@ item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedLis
641
655
  1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let line of itemLines)for(let wrappedLine of wrapTextWithAnsi(line,itemWidth)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine),renderedAnyLine=!0}}renderedAnyLine||lines.push(firstPrefix),token.loose&&!isLastItem&&lines.push("")}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>
642
656
  0),longest=0;for(let word of words)longest=Math.max(longest,visibleWidth(word));return maxWidth===void 0?longest:Math.min(longest,maxWidth)}wrapCellText(text,maxWidth,stylePrefix=""){let lines=wrapTextWithAnsi(text,Math.max(1,maxWidth));return lines.map((line,index)=>{let styleReset=index<lines.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${line}${styleReset}${stylePrefix}`})}renderTable(token,availableWidth,nextTokenType,styleContext){let lines=[],numCols=token.header.length;if(numCols===
643
657
  0)return lines;let borderOverhead=3*numCols+1,availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){let fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}let maxUnbrokenWordWidth=30,naturalWidths=[],minWordWidths=[];for(let i=0;i<numCols;i++){let headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText),minWordWidths[i]=
644
- Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a,b)=>a+b,0);if(minCellsWidth>availableForCells){minColumnWidths=
658
+ Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a3,b)=>a3+b,0);if(minCellsWidth>availableForCells){minColumnWidths=
645
659
  new Array(numCols).fill(1);let remaining=availableForCells-numCols;if(remaining>0){let totalWeight=minWordWidths.reduce((total,width)=>total+Math.max(0,width-1),0),growth=minWordWidths.map(width=>{let weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++)minColumnWidths[i]+=growth[i]??0;let allocated=growth.reduce((total,width)=>total+width,0),leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++)minColumnWidths[i]++,leftover--}
646
- minCellsWidth=minColumnWidths.reduce((a,b)=>a+b,0)}let totalNaturalWidth=naturalWidths.reduce((a,b)=>a+b,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.reduce((total,width,index)=>total+Math.max(0,width-minColumnWidths[index]),0),extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{let naturalWidth=naturalWidths[index],
647
- minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential>0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a,b)=>a+b,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;for(let i=0;i<numCols&&remaining>0;i++)columnWidths[i]<naturalWidths[i]&&(columnWidths[i]++,remaining--,grew=!0);if(!grew)break}}let topBorderCells=columnWidths.map(w=>"\u2500".repeat(w));lines.push(`\u250C\u2500${topBorderCells.
660
+ minCellsWidth=minColumnWidths.reduce((a3,b)=>a3+b,0)}let totalNaturalWidth=naturalWidths.reduce((a3,b)=>a3+b,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.reduce((total,width,index)=>total+Math.max(0,width-minColumnWidths[index]),0),extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{let naturalWidth=naturalWidths[index],
661
+ minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential>0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a3,b)=>a3+b,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;for(let i=0;i<numCols&&remaining>0;i++)columnWidths[i]<naturalWidths[i]&&(columnWidths[i]++,remaining--,grew=!0);if(!grew)break}}let topBorderCells=columnWidths.map(w2=>"\u2500".repeat(w2));lines.push(`\u250C\u2500${topBorderCells.
648
662
  join("\u2500\u252C\u2500")}\u2500\u2510`);let headerCellLines=token.header.map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),headerLineCount=Math.max(...headerCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){let rowParts=headerCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"",padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));
649
- return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}let separatorLine=`\u251C\u2500${columnWidths.map(w=>"\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),rowLineCount=Math.max(
650
- ...rowCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w=>"\u2500".repeat(w));return lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\
651
- \u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};var MouseRegion=class{child;onMouse;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){return this.child.render(width)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.child.invalidate()}};var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.
663
+ return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}let separatorLine=`\u251C\u2500${columnWidths.map(w2=>"\u2500".repeat(w2)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),rowLineCount=Math.max(
664
+ ...rowCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w2=>"\u2500".repeat(w2));return lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\
665
+ \u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};markStableRender(Markdown);var MouseRegion=class{child;onMouse;copiedLines;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){let lines=renderSharedLines(this.child,width);if(isStableRender(this.child))return lines;let copied=this.copiedLines;return copied!==void 0&&copied.length===lines.length&&copied.every((line,i)=>line===lines[i])?copied:(this.copiedLines=lines.slice(),this.copiedLines)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.copiedLines=
666
+ void 0,this.child.invalidate()}};markStableRender(MouseRegion);var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.
652
667
  child=component,this.children.push(component),this.followEnd=(options.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options.primary??!1,this.overscroll=options.overscroll??"chain",this.currentScrollbar=options.scrollbar??"hidden",this.scrollbarTrackStyle=options.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options.scrollbarHideDelayMs??
653
668
  1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(scrollbar){scrollbar!==this.currentScrollbar&&(this.
654
669
  currentScrollbar=scrollbar,scrollbar!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(width){return this.scrollbar==="always"&&width>1?width-1:width}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=
@@ -670,25 +685,27 @@ itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedInde
670
685
  matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(data,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?
671
686
  this.filteredItems:this.items}getVisibleRange(displayItems){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),displayItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,displayItems.length)}}activateItem(){let item=this.getDisplayItems()[this.selectedIndex];if(item){if(item.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=item.submenu(item.currentValue,(selectedValue,options)=>{selectedValue!==void 0&&
672
687
  (item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options?.navigateTo&&(this.navigateAfterClose=options.navigateTo),this.closeSubmenu()});else if(item.values&&item.values.length>0){let nextIndex=(item.values.indexOf(item.currentValue)+1)%item.values.length,newValue=item.values[nextIndex];item.currentValue=newValue,this.onChange(item.id,newValue)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let id=this.navigateAfterClose;this.navigateAfterClose=
673
- null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),width))}};var Spacer=class{lines;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){let result=[];for(let i=0;i<this.lines;i++)result.push("");return result}};var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
688
+ null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),width))}};var Spacer=class{lines;renderedLines=[];renderedCount=0;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){if(this.renderedCount!==this.lines){let result=[];for(let i=0;i<this.lines;i++)result.push("");this.renderedLines=result,this.renderedCount=this.lines}return this.renderedLines}};markStableRender(Spacer);var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
674
689
  `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.
675
690
  push("");let childLines=rendered[index].slice(0,sizes[index]);lines.push(...childLines);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push("")}return lines}};import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname2(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),
676
691
  "..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.
677
692
  getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}var PROGRAM_STATUS_QUERY="\x1B]7501;?\x1B\\";function isProgramStatusReply(sequence){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence)}var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,CONTROL_CHARACTERS=/[\u0000-\u001f\u007f-\u009f]+/g,MAX_MESSAGE_BYTES=2048;function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,end=0;for(let char of text){let size=Buffer.byteLength(char,"utf8");if(bytes+size>maxBytes)break;bytes+=size,end+=char.length}return text.
678
- slice(0,end)}function formatProgramStatus(status){let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8((status.message??"").replace(CONTROL_CHARACTERS," ").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~";function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.
679
- startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.
680
- test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){
681
- return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let seqEnd=1;for(;seqEnd<=remaining.length;){let candidate=remaining.
682
- slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.push(remaining[0]),pos++}return{sequences,
683
- remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str=`\x1B${String.
684
- fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.
685
- emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.
686
- buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;for(let sequence of result.sequences)this.emitDataSequence(
687
- sequence);if(this.buffer.length>0){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(
688
- sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);
693
+ slice(0,end)}function formatProgramStatus(status){let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8((status.message??"").replace(CONTROL_CHARACTERS," ").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",TERMINAL_REPLY_HEADER_PATTERN=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function isControlString(data){return data.startsWith(`${ESC}]`)||data.startsWith(`${ESC}P`)||data.startsWith(`${ESC}_`)}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"\
694
+ incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"c\
695
+ omplete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){
696
+ return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(
697
+ match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let terminalReply=isControlString(remaining)&&TERMINAL_REPLY_HEADER_PATTERN.test(remaining),seqEnd=1;for(;seqEnd<=remaining.length;){if(terminalReply&&seqEnd>2){let char=remaining[seqEnd-1];if(char===""||char===""){pos+=seqEnd;break}if(char===ESC&&seqEnd<remaining.length&&remaining[seqEnd]!=="\\"){
698
+ pos+=seqEnd-1;break}}let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.
699
+ push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>
700
+ 127){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.
701
+ pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.
702
+ pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;
703
+ for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){if(TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer))return;let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)sequence.length>2&&isControlString(sequence)?(this.emitDataSequence(sequence.slice(0,2)),this.process(sequence.slice(2))):this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.
704
+ length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.
705
+ timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);
689
706
  if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.
690
- pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env2=process.env){let configured=Number(env2.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env2.SSH_CONNECTION||env2.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{
691
- let env2=process.env.HUMAIN_TERMINAL_TUI_WRITE_LOG||process.env.PI_TUI_WRITE_LOG||"";if(!env2)return"";try{if(fs.statSync(env2).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env2,`tui-${ts}-${process.pid}.log`)}}catch{}return env2})();get kittyProtocolActive(){
707
+ pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{
708
+ let env=process.env.HUMAIN_TERMINAL_TUI_WRITE_LOG||process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){
692
709
  return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){
693
710
  this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(
694
711
  negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let programStatusOverride=process.
@@ -719,40 +736,40 @@ visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1
719
736
  controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&
720
737
  innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===
721
738
  1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(
722
- entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b){let x2=Math.max(a.x,b.x),y2=Math.max(a.y,b.y),right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.
723
- get(safeWidth);return lines||(lines=component.render(safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(
724
- child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.
725
- findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,
726
- void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,
727
- children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.
728
- gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}
729
- let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,
730
- rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,
731
- y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.
732
- end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-
733
- 1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.
734
- scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.
735
- x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.
736
- thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<
739
+ entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a3,b){let x2=Math.max(a3.x,b.x),y2=Math.max(a3.y,b.y),right=Math.min(a3.x+a3.width,b.x+b.width),bottom=Math.min(a3.y+a3.height,b.y+b.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.
740
+ get(safeWidth);return lines||(lines=renderSharedLines(component,safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)
741
+ translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>
742
+ 0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-
743
+ previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),
744
+ box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(
745
+ entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=
746
+ sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},
747
+ box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,
748
+ rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??
749
+ column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".
750
+ repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&
751
+ box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<
752
+ box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+
753
+ geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<
737
754
  lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:
738
755
  screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.
739
756
  min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},
740
757
  rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{
741
- if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.box.layer-a.box.layer||b.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{
742
- if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env2=process.env;return process.platform==="darwin"&&env2.SSH_CONNECTION===void 0&&env2.SSH_CLIENT===void 0&&env2.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.
743
- isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=
744
- Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
758
+ if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{
759
+ if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
760
+ this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.
761
+ NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
745
762
  OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;finishedRows=new Map;finishedRowsWidth=0;imageRows=new Set;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
746
763
  character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){
747
- super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=
764
+ super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.renderShared(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=
748
765
  options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(
749
766
  data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){
750
767
  this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),
751
768
  this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=
752
769
  void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:
753
770
  ""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){
754
- if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.render(width).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;
755
- for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
771
+ if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));
772
+ let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
756
773
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
757
774
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={
758
775
  transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,
@@ -770,30 +787,30 @@ let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegme
770
787
  before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.
771
788
  selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),
772
789
  this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(
773
- event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.
774
- toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))
775
- return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tu\
776
- i.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScre\
777
- en.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(
778
- button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||
779
- getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;
780
- return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===
781
- target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"rel\
782
- ease":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(
783
- event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))
784
- return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=
785
- result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.
786
- length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll===
787
- "contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.
788
- TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(
789
- this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(
790
- this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.
791
- release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=
792
- !1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,
793
- target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)
794
- return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.
795
- max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.
796
- has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)
790
+ event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.
791
+ overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.
792
+ getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.
793
+ scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(
794
+ 1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.
795
+ max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.
796
+ handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),
797
+ result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.
798
+ y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)===
799
+ "none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&
800
+ this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.
801
+ hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},
802
+ this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.
803
+ charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();
804
+ remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||
805
+ event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(
806
+ this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){
807
+ this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?
808
+ getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=
809
+ void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag=
810
+ {scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.
811
+ min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.
812
+ x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);
813
+ segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)
797
814
  selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){
798
815
  this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,
799
816
  count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.
@@ -813,7 +830,7 @@ let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",p
813
830
  length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??
814
831
  Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;
815
832
  for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(
816
- line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b)=>b.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){
833
+ line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a3,b)=>b.startCol-a3.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){
817
834
  let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){
818
835
  if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.
819
836
  rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,
@@ -823,14 +840,14 @@ clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWid
823
840
  length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}findMovedRows(screen,height){let previous=this.previousScreen,top=0;for(;top<height&&screen[top]===previous[top];)top++;let bottom=height-1;for(;bottom>top&&screen[bottom]===previous[bottom];)bottom--;let span=bottom-top+1;if(span<=MIN_ROWS_SAVED_BY_SCROLLING)
824
841
  return;let changed=0;for(let row=top;row<=bottom;row++){let line=screen[row];if(line!==previous[row]&&(changed++,isImageLine(line)||isImageLine(previous[row]??"")))return}if(changed<=MIN_ROWS_SAVED_BY_SCROLLING)return;let best=0,up=0;for(let distance=1;span-distance>best;distance++){let sameUp=0,sameDown=0;for(let row=top;row+distance<=bottom;row++)screen[row]===previous[row+distance]&&sameUp++,screen[row+distance]===previous[row]&&sameDown++;sameUp>best&&(best=sameUp,up=distance),sameDown>best&&
825
842
  (best=sameDown,up=-distance)}if(!(changed-(span-best)<MIN_ROWS_SAVED_BY_SCROLLING)){for(let row=top;row<=bottom;row++)if(isImageLine(previous[row]??""))return;return{top,bottom,up}}}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(
826
- root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.startsWith("\x1B]133;")?line.replace(OSC133_ZONE_PREFIX2,""):line);screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.
827
- extractCursorPosition(screen,height),knownRows=this.finishedRowsWidth===width?this.finishedRows:void 0,previousImageRows=this.imageRows,finishedRows=new Map,imageRows=new Set;screen=screen.map(line=>{let finished=knownRows?.get(line);return finished===void 0?(finished=this.applyLineResets([line])[0],isImageLine(finished)?imageRows.add(finished):visibleWidth(finished)>width&&(finished=sliceByColumn(finished,0,width,!0))):previousImageRows.has(finished)&&imageRows.add(finished),finishedRows.set(line,
828
- finished),finished}),this.finishedRows=finishedRows,this.finishedRowsWidth=width,this.imageRows=imageRows;let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imageAnchorsNeedRedraw=(imageRows.size>0||previousImageRows.size>0)&&screen.some((line,row)=>line!==this.previousScreen[row]&&(imageRows.has(line)||previousImageRows.has(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()===
829
- "wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&imageRows.size>0&&screen.some((line,row)=>{if(!imageRows.has(line))return!1;let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(coveredRow<screen.length&&screen[coveredRow]!==this.previousScreen[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||
830
- imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":
831
- this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&imageRows.size>0&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+
832
- 1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else{let moved=fullRedraw||redrawImages||(process.env.HUMAIN_TERMINAL_TUI_SCROLL_ROWS||process.env.PI_TUI_SCROLL_ROWS)==="0"?void 0:this.findMovedRows(screen,height);moved&&(buffer+=`\x1B[${moved.top+1};${moved.bottom+1}r`,buffer+=moved.
833
- up>0?`\x1B[${moved.bottom+1};1H${`
843
+ root,width,height,()=>this.requestRender()));let screen=this.resolveFakeCursors(nextLayout.lines.map(line=>line.startsWith("\x1B]133;")?line.replace(OSC133_ZONE_PREFIX2,""):line));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,
844
+ height);let cursorPos=this.extractCursorPosition(screen,height),knownRows=this.finishedRowsWidth===width?this.finishedRows:void 0,previousImageRows=this.imageRows,finishedRows=new Map,imageRows=new Set;screen=screen.map(line=>{let finished=knownRows?.get(line);return finished===void 0?(finished=this.applyLineResets([line])[0],isImageLine(finished)?imageRows.add(finished):visibleWidth(finished)>width&&(finished=sliceByColumn(finished,0,width,!0))):previousImageRows.has(finished)&&imageRows.add(finished),
845
+ finishedRows.set(line,finished),finished}),this.finishedRows=finishedRows,this.finishedRowsWidth=width,this.imageRows=imageRows;let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imageAnchorsNeedRedraw=(imageRows.size>0||previousImageRows.size>0)&&screen.some((line,row)=>line!==this.previousScreen[row]&&(imageRows.has(line)||previousImageRows.has(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.
846
+ toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&imageRows.size>0&&screen.some((line,row)=>{if(!imageRows.has(line))return!1;let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(coveredRow<screen.length&&screen[coveredRow]!==this.previousScreen[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,
847
+ redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol===
848
+ "iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&imageRows.size>0&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??
849
+ "")||(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else{let moved=fullRedraw||redrawImages||(process.env.HUMAIN_TERMINAL_TUI_SCROLL_ROWS||process.env.PI_TUI_SCROLL_ROWS)==="0"?void 0:this.findMovedRows(screen,height);moved&&(buffer+=`\x1B[${moved.top+1};${moved.
850
+ bottom+1}r`,buffer+=moved.up>0?`\x1B[${moved.bottom+1};1H${`
834
851
  `.repeat(moved.up)}`:`\x1B[${moved.top+1};1H${"\x1BM".repeat(-moved.up)}`,buffer+="\x1B[r");for(let row=0;row<height;row++){if(!fullRedraw&&!imagesNeedRedraw){let shown=this.previousScreen[row];if(moved&&row>=moved.top&&row<=moved.bottom){let from=row+moved.up;shown=from>=moved.top&&from<=moved.bottom?this.previousScreen[from]:void 0}if(screen[row]===shown)continue}buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`}}cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,
835
852
  cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&
836
853
  end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.
@@ -838,59 +855,36 @@ indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let para
838
855
  line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.
839
856
  maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.previousLines=[],this.
840
857
  previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
841
- `)}collectKittyImageIds(lines){let ids=new Set;for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??
842
- "";if(isImageLine(line)||visibleWidth(line)>0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,
843
- i),expandedLastChanged=Math.max(expandedLastChanged,blockEnd))}};return expandForLines(this.previousLines),expandForLines(newLines),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}deleteChangedKittyImages(firstChanged,lastChanged){if(firstChanged<0||lastChanged<firstChanged)return"";let ids=new Set,maxLine=Math.min(lastChanged,this.previousLines.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(this.previousLines[i]??""))ids.add(id);return this.
844
- deleteKittyImages(ids)}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height,previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.hardwareCursorRow,
845
- computeLineDiff=targetRow=>{let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},newLines=this.render(width);this.hasOverlayEntries&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height);newLines=this.applyLineResets(newLines);let fullRender=clear=>{this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.
846
- append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<newLines.length;i++){i>0&&output2.append(`\r
858
+ `)}rawLines=[];finishedLines=[];finishLines(raw){let previousRaw=this.rawLines,previousFinished=this.finishedLines,lines=new Array(raw.length),single=[""],imageLines=0;for(let i=0;i<raw.length;i++){let line=raw[i],finished;i<previousRaw.length&&line===previousRaw[i]?finished=previousFinished[i]:(single[0]=line,finished=this.applyLineResets(single)[0]),finished===line&&imageLines++,lines[i]=finished}return this.rawLines=raw,this.finishedLines=lines,{lines,imageLines}}collectKittyImageIds(lines){let ids=new Set;
859
+ for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??"";if(isImageLine(line)||visibleWidth(line)>
860
+ 0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(expandedLastChanged,
861
+ blockEnd))}};return expandForLines(this.previousLines),expandForLines(newLines),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}deleteChangedKittyImages(firstChanged,lastChanged){if(firstChanged<0||lastChanged<firstChanged||this.previousKittyImageIds.size===0)return"";let ids=new Set,maxLine=Math.min(lastChanged,this.previousLines.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(this.previousLines[i]??""))ids.add(id);return this.deleteKittyImages(
862
+ ids)}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height,previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.hardwareCursorRow,computeLineDiff=targetRow=>{
863
+ let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},newLines=this.resolveFakeCursors(this.render(width));this.hasOverlayEntries&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height),finished=this.finishLines(newLines);newLines=finished.lines;let imagesShown=finished.imageLines>0||this.previousKittyImageIds.size>0,collectKittyImageIds=lines=>imagesShown?this.collectKittyImageIds(lines):
864
+ new Set,fullRender=clear=>{this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<newLines.length;i++){i>0&&output2.append(`\r
847
865
  `);let line=newLines[i],imageReservedRows=isImageLine(line)?this.getKittyImageReservedRows(newLines,i):1;if(imageReservedRows>1&&imageReservedRows<=height){for(let row=1;row<imageReservedRows;row++)output2.append(`\r
848
866
  `);output2.append(`\x1B[${imageReservedRows-1}A`),output2.append(line),output2.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}output2.append(line)}output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=this.cursorRow,clear?this.maxLinesRendered=newLines.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length);let bufferLength=Math.max(height,newLines.length);this.previousViewportTop=Math.max(0,
849
- bufferLength-height),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"pi-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.
867
+ bufferLength-height),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"pi-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.
850
868
  length}, new=${newLines.length}, height=${height})
851
869
  `;fs2.mkdirSync(path3.dirname(logPath),{recursive:!0}),fs2.appendFileSync(logPath,msg)};if(this.previousLines.length===0&&!widthChanged&&!heightChanged){logRedraw("first render"),fullRender(!1);return}if(widthChanged){logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`),fullRender(!0);return}if(heightChanged&&!isTermuxSession()){logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`),fullRender(!0);return}if(this.getClearOnShrink()&&newLines.length<this.maxLinesRendered&&
852
870
  !this.hasOverlayEntries){logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),fullRender(!0);return}let firstChanged=-1,lastChanged=-1,maxLines=Math.max(newLines.length,this.previousLines.length);for(let i=0;i<maxLines;i++){let oldLine=i<this.previousLines.length?this.previousLines[i]:"",newLine=i<newLines.length?newLines[i]:"";oldLine!==newLine&&(firstChanged===-1&&(firstChanged=i),lastChanged=i)}let appendedLines=newLines.length>this.previousLines.length;if(appendedLines&&(firstChanged===
853
- -1&&(firstChanged=this.previousLines.length),lastChanged=newLines.length-1),firstChanged!==-1){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.lastChanged}let appendStart=appendedLines&&firstChanged===this.previousLines.length&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,newLines.length),this.previousViewportTop=prevViewportTop,this.previousHeight=height;return}
854
- if(firstChanged>=newLines.length){if(this.previousLines.length>newLines.length){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),output2.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let targetRow=Math.max(0,newLines.length-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0);return}let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?output2.append(`\x1B\
855
- [${lineDiff2}B`):lineDiff2<0&&output2.append(`\x1B[${-lineDiff2}A`),output2.append("\r");let extraLines=this.previousLines.length-newLines.length;if(extraLines>height){logRedraw(`extraLines > height (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=newLines.length===0?0:1;extraLines>0&&clearStartOffset>0&&output2.append(`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)output2.append("\r\x1B[2K"),i<extraLines-1&&output2.append("\x1B[1B");let moveBack=Math.max(0,extraLines-
856
- 1+clearStartOffset);moveBack>0&&output2.append(`\x1B[${moveBack}A`),output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<prevViewportTop){logRedraw(`firstChanged < viewportTop (${firstChanged}\
857
- < ${prevViewportTop})`),fullRender(!0);return}let output=new BoundedTerminalWriter(data=>this.terminal.write(data));output.append("\x1B[?2026h"),output.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),moveToBottom=height-1-currentScreenRow;moveToBottom>0&&output.
858
- append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
871
+ -1&&(firstChanged=this.previousLines.length),lastChanged=newLines.length-1),firstChanged!==-1&&imagesShown){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.lastChanged}let appendStart=appendedLines&&firstChanged===this.previousLines.length&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,newLines.length),this.previousViewportTop=prevViewportTop,this.previousHeight=
872
+ height;return}if(firstChanged>=newLines.length){if(this.previousLines.length>newLines.length){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),output2.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let targetRow=Math.max(0,newLines.length-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0);return}let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?output2.
873
+ append(`\x1B[${lineDiff2}B`):lineDiff2<0&&output2.append(`\x1B[${-lineDiff2}A`),output2.append("\r");let extraLines=this.previousLines.length-newLines.length;if(extraLines>height){logRedraw(`extraLines > height (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=newLines.length===0?0:1;extraLines>0&&clearStartOffset>0&&output2.append(`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)output2.append("\r\x1B[2K"),i<extraLines-1&&output2.append("\x1B[1B");let moveBack=Math.
874
+ max(0,extraLines-1+clearStartOffset);moveBack>0&&output2.append(`\x1B[${moveBack}A`),output2.append("\x1B[?2026l"),output2.flush(),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<prevViewportTop){logRedraw(`firstChanged < viewportTop\
875
+ (${firstChanged} < ${prevViewportTop})`),fullRender(!0);return}let output=new BoundedTerminalWriter(data=>this.terminal.write(data));output.append("\x1B[?2026h"),output.append(this.deleteChangedKittyImages(firstChanged,lastChanged));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),moveToBottom=height-1-currentScreenRow;moveToBottom>
876
+ 0&&output.append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
859
877
  `.repeat(scroll)),prevViewportTop+=scroll,viewportTop+=scroll,hardwareCursorRow=moveTargetRow}let lineDiff=computeLineDiff(moveTargetRow);lineDiff>0?output.append(`\x1B[${lineDiff}B`):lineDiff<0&&output.append(`\x1B[${-lineDiff}A`),output.append(appendStart?`\r
860
878
  `:"\r");let renderEnd=Math.min(lastChanged,newLines.length-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
861
879
  `);let line=newLines[i],isImage=isImageLine(line),imageReservedRows=isImage?this.getKittyImageReservedRows(newLines,i,renderEnd):1;if(imageReservedRows>1){let imageStartScreenRow=i-viewportTop;if(imageStartScreenRow<0||imageStartScreenRow+imageReservedRows>height){logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`),fullRender(!0);return}output.append("\x1B[2K");for(let row=1;row<imageReservedRows;row++)output.append(`\r
862
- \x1B[2K`);output.append(`\x1B[${imageReservedRows-1}A`),output.append(line),output.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}if(output.append("\x1B[2K"),!isImage&&visibleWidth(line)>width){let crashLogPath=path3.join(this.logDirectory??os.tmpdir(),"pi-tui-crash.log"),crashData=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${width}`,`Line ${i} visible width: ${visibleWidth(line)}`,"","=== All rendered lines ===",...newLines.map((l3,idx)=>`[${idx}] (w=${visibleWidth(
863
- l3)}) ${l3}`),""].join(`
880
+ \x1B[2K`);output.append(`\x1B[${imageReservedRows-1}A`),output.append(line),output.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}if(output.append("\x1B[2K"),!isImage&&visibleWidth(line)>width){let crashLogPath=path3.join(this.logDirectory??os.tmpdir(),"pi-tui-crash.log"),crashData=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${width}`,`Line ${i} visible width: ${visibleWidth(line)}`,"","=== All rendered lines ===",...newLines.map((l,idx)=>`[${idx}] (w=${visibleWidth(
881
+ l)}) ${l}`),""].join(`
864
882
  `);fs2.mkdirSync(path3.dirname(crashLogPath),{recursive:!0}),fs2.writeFileSync(crashLogPath,crashData),this.stop();let errorMsg=[`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${crashLogPath}`].join(`
865
883
  `);throw new Error(errorMsg)}output.append(line)}let finalCursorRow=renderEnd;if(this.previousLines.length>newLines.length){if(renderEnd<newLines.length-1){let moveDown=newLines.length-1-renderEnd;output.append(`\x1B[${moveDown}B`),finalCursorRow=newLines.length-1}let extraLines=this.previousLines.length-newLines.length;for(let i=newLines.length;i<this.previousLines.length;i++)output.append(`\r
866
884
  \x1B[2K`);output.append(`\x1B[${extraLines}A`)}if(output.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let debugDir="/tmp/tui";fs2.mkdirSync(debugDir,{recursive:!0});let debugPath=path3.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,`renderEnd: ${renderEnd}`,`finalCur\
867
885
  sorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${newLines.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(newLines,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${output.length} chars written in bounded chunks]`].join(`
868
- `);fs2.writeFileSync(debugPath,debugData)}output.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=finalCursorRow,this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines){
869
- if(!cursorPos||totalLines<=0){this.terminal.hideCursor();return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow,buffer="";rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,buffer&&this.terminal.write(buffer),this.hardwareCursorRow=targetRow,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};function stringReplaceAll(string,substring,postfix){let index=string.indexOf(substring);if(index===-1)return string;let substringLength=substring.length,endIndex=0,returnValue="";do returnValue+=string.slice(endIndex,index)+substring+postfix,endIndex=index+substringLength,index=string.indexOf(substring,endIndex);while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}function stringEncaseCRLFWithFirstIndex(string,prefix,postfix,index){let endIndex=0,returnValue="";do{let isGotCR=string[index-
870
- 1]==="\r";returnValue+=string.slice(endIndex,isGotCR?index-1:index)+prefix+(isGotCR?`\r
871
- `:`
872
- `)+postfix,endIndex=index+1,index=string.indexOf(`
873
- `,endIndex)}while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}var wrapAnsi16=(offset=0)=>code=>`\x1B[${code+offset}m`,wrapAnsi256=(offset=0)=>code=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,wrapUnderlineAnsi=code=>`\x1B[58;5;${code<90?code-30:code-90+8}m`,styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[
874
- 8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,
875
- 49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:[
876
- "58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},modifierNames=Object.keys(styles.modifier),foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor),underlineColorNames=Object.keys(styles.underlineColor),colorNames=[...foregroundColorNames,...backgroundColorNames];
877
- function assembleStyles(){let codes=new Map;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(Number.parseInt(style[0],10),style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",
878
- styles.underlineColor.close="\x1B[59m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(10),styles.bgColor.ansi256=wrapAnsi256(10),styles.bgColor.ansi16m=wrapAnsi16m(10),styles.underlineColor.ansi=wrapUnderlineAnsi,styles.underlineColor.ansi256=wrapAnsi256(20),styles.underlineColor.ansi16m=wrapAnsi16m(20),Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){return red===green&&green===blue?red<8?16:
879
- red>248?231:Math.round((red-8)/247*24)+232:16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[\da-f]{6}|[\da-f]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;colorString.length===3&&(colorString=[...colorString].map(character=>character+character).join(""));let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:hex=>styles.
880
- rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));return value===2&&(result+=60),result},enumerable:!1},
881
- rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:hex=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:!1}}),styles}var ansiStyles=assembleStyles(),ansi_styles_default=ansiStyles;import process2 from"node:process";import os2 from"node:os";import tty from"node:tty";function hasFlag(flag,argv=globalThis.Deno?globalThis.Deno.args:process2.argv){let prefix=flag.startsWith("-")?"":flag.length===1?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}var{env}=process2,flagForceColor;hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")?flagForceColor=
882
- 0:(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))&&(flagForceColor=1);function hasNumericForceColor(){return/^\d+$/.test(env.FORCE_COLOR)}function envForceColor(){if("FORCE_COLOR"in env){if(env.FORCE_COLOR==="false")return 0;if(env.FORCE_COLOR==="true"||env.FORCE_COLOR.length===0)return 1;if(hasNumericForceColor())return Math.min(Number.parseInt(env.FORCE_COLOR,10),3)}}function translateLevel(level){return level===0?!1:{level,hasBasic:!0,has256:level>=2,has16m:level>=
883
- 3}}function _supportsColor(haveStream,{streamIsTTY,sniffFlags=!0}={}){let noFlagForceColor=envForceColor();noFlagForceColor!==void 0&&(flagForceColor=noFlagForceColor);let forceColor=sniffFlags?flagForceColor:noFlagForceColor;if(forceColor===0)return 0;if(sniffFlags){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2}if(forceColor!==void 0&&hasNumericForceColor())return forceColor;if("TF_BUILD"in env&&"AGENT_NAME"in env)return 1;if(haveStream&&
884
- !streamIsTTY&&forceColor===void 0)return 0;let min=forceColor||0;if(env.TERM==="dumb")return min;if(process2.platform==="win32"){let osRelease=os2.release().split(".");return Number(osRelease[0])>=10&&Number(osRelease[2])>=10586?Number(osRelease[2])>=14931?3:2:1}if("CI"in env)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(key=>key in env)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(sign=>sign in env)||env.CI_NAME==="codeship"?1:min;if("TEAMCITY_VERSION"in env)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.
885
- test(env.TEAMCITY_VERSION)?1:0;if(env.COLORTERM==="truecolor"||env.TERM==="xterm-kitty"||env.TERM==="xterm-ghostty"||env.TERM==="wezterm")return 3;if("TERM_PROGRAM"in env){let version=Number.parseInt((env.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}return/-256(?:color)?$/i.test(env.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)||"COLORTERM"in env?1:min}function createSupportsColor(stream,options={}){
886
- let level=_supportsColor(stream,{streamIsTTY:stream&&stream.isTTY,...options});return translateLevel(level)}var supportsColor={stdout:createSupportsColor({isTTY:tty.isatty(1)}),stderr:createSupportsColor({isTTY:tty.isatty(2)})},supports_color_default=supportsColor;var{stdout:stdoutColor,stderr:stderrColor}=supports_color_default,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),LEVEL=Symbol("LEVEL"),styles2=Object.create(null),assertValidLevel=level=>{if(!Number.isSafeInteger(level)||level<0||level>3)throw new Error("The `level` should be an integer from 0 to 3")},levelDescriptor={enumerable:!0,get(){return this[LEVEL]},set(level){assertValidLevel(level),this[LEVEL]=level}},applyOptions=(object,options={})=>{options.level!==
887
- void 0&&assertValidLevel(options.level);let colorLevel=stdoutColor?stdoutColor.level:0;object[LEVEL]=options.level===void 0?colorLevel:options.level};var chalkFactory=options=>{let chalk2=(...strings)=>strings.join(" ");return applyOptions(chalk2,options),Object.setPrototypeOf(chalk2,createChalk.prototype),chalk2};function createChalk(options){return chalkFactory(options)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default))styles2[styleName]={get(){let builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(
888
- this,styleName,{value:builder}),builder}};styles2.visible={get(){let builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};var createModelConverters=(model,type)=>{let style=ansi_styles_default[type];if(model==="rgb"){let ansi2=(red,green,blue)=>style.ansi(ansi_styles_default.rgbToAnsi(red,green,blue));return[ansi2,ansi2,(red,green,blue)=>style.ansi256(ansi_styles_default.rgbToAnsi256(red,green,blue)),style.ansi16m]}if(model==="hex"){let ansi2=hex=>style.
889
- ansi(ansi_styles_default.hexToAnsi(hex));return[ansi2,ansi2,hex=>style.ansi256(ansi_styles_default.hexToAnsi256(hex)),hex=>style.ansi16m(...ansi_styles_default.hexToRgb(hex))]}let ansi=code=>style.ansi(ansi_styles_default.ansi256ToAnsi(code));return[ansi,ansi,style.ansi256,style.ansi256]},usedModels=["rgb","hex","ansi256"];for(let model of usedModels){let capitalizedModel=model[0].toUpperCase()+model.slice(1);for(let[styleName,type]of[[model,"color"],["bg"+capitalizedModel,"bgColor"],["underline"+
890
- capitalizedModel,"underlineColor"]]){let{close}=ansi_styles_default[type],converters=createModelConverters(model,type);styles2[styleName]={get(){let styleFunction=function(first,second,third){let open=converters[this.level](first,second,third);return createBuilder(this,createStyler(open,close,this[STYLER]),this[IS_EMPTY])};return Object.defineProperty(this,styleName,{value:styleFunction}),styleFunction}}}}var proto=Object.defineProperties(()=>{},{...styles2,level:{enumerable:!0,get(){return this[GENERATOR].
891
- level},set(level){this[GENERATOR].level=level}}}),createStyler=(open,close,parent)=>{let openAll,closeAll;return parent===void 0?(openAll=open,closeAll=close):(openAll=parent.openAll+open,closeAll=close+parent.closeAll),{open,close,openAll,closeAll,parent}},createBuilder=(self,_styler,_isEmpty)=>{let builder=(...arguments_)=>arguments_.length===1?applyStyle(builder,""+arguments_[0]):arguments_.length===2?applyStyle(builder,`${arguments_[0]??""} ${arguments_[1]??""}`):applyStyle(builder,arguments_.
892
- join(" "));return Object.setPrototypeOf(builder,proto),builder[GENERATOR]=self[GENERATOR]??self,builder[STYLER]=_styler,builder[IS_EMPTY]=_isEmpty,builder},applyStyle=(self,string)=>{if(self[GENERATOR][LEVEL]<=0||!string)return self[IS_EMPTY]?"":string;let styler=self[STYLER];if(styler===void 0)return string;let{openAll,closeAll}=styler;if(string.includes("\x1B"))for(;styler!==void 0;)string=stringReplaceAll(string,styler.close,styler.open),styler=styler.parent;let lfIndex=string.indexOf(`
893
- `);return lfIndex!==-1&&(string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex)),openAll+string+closeAll};Object.defineProperties(createChalk.prototype,{...styles2,level:levelDescriptor});var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1);var core_default=import_core.default;function bash(hljs2){let regex=hljs2.regex,VAR={},BRACED_VAR={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[VAR]}]};Object.assign(VAR,{className:"variable",variants:[{begin:regex.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},BRACED_VAR]});let SUBST={className:"subst",begin:/\$\(/,end:/\)/,contains:[hljs2.BACKSLASH_ESCAPE]},COMMENT=hljs2.inherit(hljs2.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),HERE_DOC={begin:/<<-?\s*(?=\w+)/,starts:{contains:[hljs2.END_SAME_AS_BEGIN(
886
+ `);fs2.writeFileSync(debugPath,debugData)}output.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=finalCursorRow,this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines){
887
+ if(!cursorPos||totalLines<=0){this.terminal.hideCursor();return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow,buffer="";rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,buffer&&this.terminal.write(buffer),this.hardwareCursorRow=targetRow,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1);var core_default=import_core.default;function bash(hljs2){let regex=hljs2.regex,VAR={},BRACED_VAR={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[VAR]}]};Object.assign(VAR,{className:"variable",variants:[{begin:regex.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},BRACED_VAR]});let SUBST={className:"subst",begin:/\$\(/,end:/\)/,contains:[hljs2.BACKSLASH_ESCAPE]},COMMENT=hljs2.inherit(hljs2.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),HERE_DOC={begin:/<<-?\s*(?=\w+)/,starts:{contains:[hljs2.END_SAME_AS_BEGIN(
894
888
  {begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},QUOTE_STRING={className:"string",begin:/"/,end:/"/,contains:[hljs2.BACKSLASH_ESCAPE,VAR,SUBST]};SUBST.contains.push(QUOTE_STRING);let ESCAPED_QUOTE={match:/\\"/},APOS_STRING={className:"string",begin:/'/,end:/'/},ESCAPED_APOS={match:/\\'/},ARITHMETIC={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},hljs2.NUMBER_MODE,VAR]},SH_LIKE_SHELLS=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],KNOWN_SHEBANG=hljs2.
895
889
  SHEBANG({binary:`(${SH_LIKE_SHELLS.join("|")})`,relevance:10}),FUNCTION={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[hljs2.inherit(hljs2.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},KEYWORDS3=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],LITERALS3=["true","false"],PATH_MODE={match:/(\/[a-z._-]+)+/},SHELL_BUILT_INS=["break","cd","continue","eval","exec","exit","export","getopts","hash",
896
890
  "pwd","readonly","return","shift","test","times","trap","umask","unset"],BASH_BUILT_INS=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],ZSH_BUILT_INS=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","e\
@@ -1081,14 +1075,16 @@ GETTER_OR_SETTER,{match:/\$[(.]/}]}}function typescript(hljs2){let regex=hljs2.r
1081
1075
  meta",relevance:10,begin:/^\s*['"]use strict['"]/},TS_SPECIFIC_KEYWORDS=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],KEYWORDS$1={$pattern:IDENT_RE2,keyword:KEYWORDS2.concat(TS_SPECIFIC_KEYWORDS),literal:LITERALS2,built_in:BUILT_INS2.concat(TYPES3),"variable.language":BUILT_IN_VARIABLES2},DECORATOR={className:"meta",begin:"@"+IDENT_RE$1},swapMode=(mode,label,replacement)=>{let indx=mode.contains.findIndex(m=>m.label===
1082
1076
  label);if(indx===-1)throw new Error("can not find mode to replace");mode.contains.splice(indx,1,replacement)};Object.assign(tsLanguage.keywords,KEYWORDS$1),tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);let ATTRIBUTE_HIGHLIGHT=tsLanguage.contains.find(c2=>c2.scope==="attr"),OPTIONAL_KEY_OR_ARGUMENT=Object.assign({},ATTRIBUTE_HIGHLIGHT,{match:regex.concat(IDENT_RE$1,regex.lookahead(/\s*\?:/))});tsLanguage.exports.PARAMS_CONTAINS.push([tsLanguage.exports.CLASS_REFERENCE,ATTRIBUTE_HIGHLIGHT,OPTIONAL_KEY_OR_ARGUMENT]),
1083
1077
  tsLanguage.contains=tsLanguage.contains.concat([DECORATOR,NAMESPACE,INTERFACE,OPTIONAL_KEY_OR_ARGUMENT]),swapMode(tsLanguage,"shebang",hljs2.SHEBANG()),swapMode(tsLanguage,"use_strict",USE_STRICT);let functionDeclaration=tsLanguage.contains.find(m=>m.label==="func.def");return functionDeclaration.relevance=0,Object.assign(tsLanguage,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),tsLanguage}function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html,index){
1084
- let semicolonIndex=html.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python,java,go,javascript,json,cpp,typescript,php,ruby,c,csharp,nix,bash,rust,scala,kotlin,swift,dart,groovy,perl,lua},hljs=core_default;for(let[name,language]of Object.entries(eagerLanguages))hljs.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./es-N6YFJOD7.js").then(module=>{hljs=module.default,resolve()},()=>{resolve()})})})),
1085
- allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==
1086
- -1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html,index){
1087
- if(!html.startsWith("<span",index))return!1;let nextChar=html[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
1078
+ let semicolonIndex=html.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python,java,go,javascript,json,cpp,typescript,php,ruby,c,csharp,nix,bash,rust,scala,kotlin,swift,dart,groovy,perl,lua},hljs=core_default,eagerLanguagesRegistered=!1;function registerEagerLanguages(){if(!eagerLanguagesRegistered){eagerLanguagesRegistered=!0;for(let[name,language]of Object.entries(eagerLanguages))hljs.registerLanguage(name,language)}}var allLanguagesPromise,allLanguagesLoaded=!1;function loadAllHighlightLanguages(){return registerEagerLanguages(),allLanguagesPromise||
1079
+ (allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./es-YEFEOGR3.js").then(module=>{hljs=module.default,allLanguagesLoaded=!0,resolve()},()=>{allLanguagesLoaded=!0,resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))
1080
+ return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-
1081
+ 1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html,index){if(!html.startsWith("<span",index))return!1;let nextChar=html[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
1088
1082
  `||nextChar==="\r"}function renderHighlightedHtml(html,theme2={}){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?textBuffer.split(`
1089
1083
  `).map(line=>line&&formatter(line)).join(`
1090
1084
  `):textBuffer,textBuffer=""},index=0;for(;index<html.length;){if(isSpanOpenTagStart(html,index)){let tagEndIndex=html.indexOf(">",index+5);if(tagEndIndex!==-1){flushText();let tag=html.slice(index,tagEndIndex+1),scope=getScopeFromSpanTag(tag);scopes.push(scope),index=tagEndIndex+1;continue}}if(html.startsWith(SPAN_CLOSE,index)){flushText(),scopes.length>0&&scopes.pop(),index+=SPAN_CLOSE.length;continue}if(html[index]==="&"){let decoded=decodeHtmlEntityAt(html,index);if(decoded){textBuffer+=decoded.
1091
- text,index+=decoded.length;continue}}textBuffer+=html[index],index++}return flushText(),output}function highlight(code,options={}){let html=options.language?hljs.highlight(code,{language:options.language,ignoreIllegals:options.ignoreIllegals}).value:hljs.highlightAuto(code,options.languageSubset).value;return renderHighlightedHtml(html,options.theme)}function supportsLanguage(name){return hljs.getLanguage(name)!==void 0}var SYSTEM_THEME_NAME="system",FAMILIES={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{
1085
+ text,index+=decoded.length;continue}}textBuffer+=html[index],index++}return flushText(),output}function highlight(code,options={}){registerEagerLanguages();let html=options.language?hljs.highlight(code,{language:options.language,ignoreIllegals:options.ignoreIllegals}).value:hljs.highlightAuto(code,options.languageSubset).value;return renderHighlightedHtml(html,options.theme)}var onDemandLoaded,askedBeforeOnDemand=!1,missedLanguages=new Set;function loadOnDemand(){loadAllHighlightLanguages().then(
1086
+ ()=>{let languages=new Set([...missedLanguages].filter(name=>hljs.getLanguage(name)!==void 0));missedLanguages.clear(),languages.size>0&&onDemandLoaded?.(languages)})}function loadAllHighlightLanguagesOnDemand(onLoaded){onDemandLoaded=onLoaded,askedBeforeOnDemand&&!allLanguagesPromise&&loadOnDemand()}function supportsLanguage(name){return registerEagerLanguages(),hljs.getLanguage(name)!==void 0?!0:(allLanguagesLoaded||missedLanguages.add(name.toLowerCase()),onDemandLoaded?allLanguagesPromise||loadOnDemand():
1087
+ askedBeforeOnDemand=!0,!1)}var SYSTEM_THEME_NAME="system",FAMILIES={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{
1092
1088
  min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},TOKEN_FAMILIES={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"\
1093
1089
  neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",
1094
1090
  customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"\
@@ -1104,47 +1100,57 @@ t","success","error","warning"],["background","selectedBg",...TOOL_PANELS],"read
1104
1100
  level:"readable"},{token:"toolOutput",on:["background",...TOOL_PANELS],level:"readable"},...each(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...MESSAGE_PANELS],"readable"),{token:"mdCodeBlock",on:["background",...MESSAGE_PANELS,...TOOL_PANELS],level:"readable"},...each(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...TOOL_PANELS],"readable"),...each(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable",
1105
1101
  "syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...each(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...each(["mdQuoteBorder","mdHr"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarT\
1106
1102
  humb",on:["scrollbarTrack"],level:"thumb"},...THINKING.map((token,index)=>({token,on:["background"],level:THINKING_LEVELS[index]}))],READABLE_FLOOR={dark:"readable",light:"subtle"},FOREGROUND_LEVEL="emphasis",FOREGROUND_TOKENS=["text","userMessageText","toolTitle"],TEXT_MINIMUM_WCAG_CONTRAST=4.5,SOLVE_ORDER=(()=>{let order=[],visit=token=>{if(!order.includes(token)){for(let rule of RULES)if(rule.token===token)for(let surface of rule.on)surface!=="background"&&visit(surface);order.push(token)}};for(let rule of RULES)
1107
- visit(rule.token);return order})();function oklabLightness(color){return colorToOklch(rgbColor(color.r,color.g,color.b)).l}function relativeLuminance({r,g,b}){let linear=channel=>{let value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4};return .2126*linear(r)+.7152*linear(g)+.0722*linear(b)}function wcagContrast(first,second){let a=relativeLuminance(first),b=relativeLuminance(second);return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}function terminalAppearance(background,foreground){
1103
+ visit(rule.token);return order})();function oklabLightness(color){return colorToOklch(rgbColor(color.r,color.g,color.b)).l}function relativeLuminance({r,g,b}){let linear=channel=>{let value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4};return .2126*linear(r)+.7152*linear(g)+.0722*linear(b)}function wcagContrast(first,second){let a3=relativeLuminance(first),b=relativeLuminance(second);return(Math.max(a3,b)+.05)/(Math.min(a3,b)+.05)}function terminalAppearance(background,foreground){
1108
1104
  let white={r:255,g:255,b:255},black={r:0,g:0,b:0},whiteContrast=wcagContrast(white,background),blackContrast=wcagContrast(black,background);if(foreground){let foregroundL=oklabLightness(foreground),backgroundL=oklabLightness(background);if(Math.abs(foregroundL-backgroundL)>.05){let appearance=foregroundL>backgroundL?"dark":"light";if((appearance==="dark"?whiteContrast:blackContrast)>=TEXT_MINIMUM_WCAG_CONTRAST)return appearance}}return whiteContrast>=blackContrast?"dark":"light"}var clamp2=(value,min,max)=>Math.
1109
1105
  min(max,Math.max(min,value));function hexOf({r,g,b}){return`#${[r,g,b].map(channel=>Math.round(channel).toString(16).padStart(2,"0")).join("")}`}function bellWeight(lightness){let gaussian=x2=>Math.exp(-((x2-.5)**2)/.125);return(gaussian(lightness)-gaussian(0))/(1-gaussian(0))}function saturationCurve({saturation:{min,max}},lightness){let floor=max>0?min/max:1;return floor+(1-floor)*bellWeight(lightness)}function levelTarget(level,appearance,surfaceL){let curve=LEVELS[level][appearance];if(!(surfaceL<
1110
1106
  curve.reachable[0]||surfaceL>curve.reachable[1]))return curve.coefficients.reduce((sum,coefficient,power)=>sum+coefficient*surfaceL**power,0)}function generateSystemThemeColors(input){let saturation=clamp2(input.saturation??1,0,1),{background,foreground}=input;if(!background)return indexedColors(saturation,input.appearanceHint);let palette=input.palette?.length===16?input.palette.map(sourceOf):void 0,appearance=terminalAppearance(background,foreground),lighter=appearance==="dark",extreme=lighter?
1111
1107
  1:0,backgroundL=oklabLightness(background),paint=(token,oklabL)=>{let lightness=oklabToOkhslLightness(oklabL),family=FAMILIES[TOKEN_FAMILIES[token]];if(!palette){let{min,max}=family.saturation;return okhslColor(family.hue,(min+(max-min)*bellWeight(lightness))*saturation,lightness)}return anchored(palette[TOKEN_SLOTS[token]??family.slot],family,lightness,saturation)},target=(level,surfaceL,t)=>{let reached=levelTarget(level,appearance,surfaceL);if(reached===void 0&&t===0)return;let distance=(reached??
1112
- extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfaceL)??extreme)-surfaceL,compressed=Math.abs(distance)>Math.abs(floor)?distance-(distance-floor)*Math.min(t,1):distance;return surfaceL+compressed*(1-Math.max(0,t-1))},extremeText=lighter?{r:255,g:255,b:255}:{r:0,g:0,b:0},readable=color=>wcagContrast(extremeText,color)>=TEXT_MINIMUM_WCAG_CONTRAST,limitPanel=(token,l3)=>{let color=paint(token,l3);if(readable(color))return color;let[low,high]=[backgroundL,l3];for(let index=0;index<
1113
- 20;index++){let middle=(low+high)/2;readable(paint(token,middle))?low=middle:high=middle}return paint(token,low)},solve=t=>{let colors2=new Map([["background",background]]);for(let token of SOLVE_ORDER){let targets=[];for(let rule of RULES)if(rule.token===token)for(let surface of rule.on){let value=target(rule.level,oklabLightness(colors2.get(surface)??background),t);if(value===void 0||value<0||value>1)return;targets.push(value)}let l3=lighter?Math.max(...targets):Math.min(...targets);colors2.set(
1114
- token,PANELS.includes(token)?limitPanel(token,l3):paint(token,l3))}return colors2},relaxation=0,colors=solve(0);if(!colors){let[low,high]=[0,2];colors=solve(high);for(let index=0;index<20;index++){let middle=(low+high)/2,attempt=solve(middle);attempt?[high,colors]=[middle,attempt]:low=middle}relaxation=high}let solved=colors??new Map,surfacesOf=token=>RULES.filter(rule=>rule.token===token).flatMap(rule=>rule.on.map(surface=>solved.get(surface)??background)),result={};for(let token of Object.keys(
1115
- TOKEN_FAMILIES)){let color=solved.get(token);result[token]=color?hexOf(color):""}for(let token of FOREGROUND_TOKENS){let surfaces=surfacesOf(token),text=solved.get(token);if(foreground){let targets=surfaces.map(surface=>target(FOREGROUND_LEVEL,oklabLightness(surface),relaxation));if(targets.every(value=>value!==void 0&&value>=0&&value<=1)){let needed=lighter?Math.max(...targets):Math.min(...targets),foregroundL=oklabLightness(foreground);if(lighter?foregroundL>=needed:foregroundL<=needed){result[token]=
1116
- "";continue}text=anchored(sourceOf(foreground),FAMILIES.neutral,oklabToOkhslLightness(needed),saturation)}}text&&(result[token]=hexOf(withTextContrast(text,surfaces,lighter)))}return{colors:result,dim:[],appearance}}function okhslOf({r,g,b}){return colorToOkhsl(rgbColor(r,g,b))}function sourceOf(color){return{...okhslOf(color),chroma:colorToOklch(rgbColor(color.r,color.g,color.b)).c}}function anchored(source2,family,lightness,saturation){let anchor=saturationCurve(family,source2.l),falloff=anchor>
1117
- 0?Math.min(1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source2.h,source2.s*falloff*saturation,lightness),cap=source2.chroma*falloff*saturation,{l:l3,c:c2}=colorToOklch(color);return c2<=cap?color:colorToRgb(oklchColor(l3,cap,source2.h))}function withTextContrast(color,surfaces,lighter){let meets=candidate=>surfaces.every(surface=>wcagContrast(candidate,surface)>=TEXT_MINIMUM_WCAG_CONTRAST);if(meets(color))return color;let{h:h2,s,l:l3}=okhslOf(color),at2=lightness=>okhslColor(h2,
1118
- s,lightness),extreme=lighter?1:0;if(!meets(at2(extreme)))return at2(extreme);let[low,high]=[l3,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at2(middle))?high=middle:low=middle}return at2(high)}function indexedColors(saturation,appearance){let colors={},dim=[];for(let[token,familyName]of Object.entries(TOKEN_FAMILIES)){if(PANELS.includes(token)){colors[token]="";continue}let neutral=familyName==="neutral";colors[token]=!neutral&&saturation>0?TOKEN_SLOTS[token]??FAMILIES[familyName].
1119
- slot:"",neutral&&!FOREGROUND_TOKENS.includes(token)&&dim.push(token)}return{colors,dim,appearance}}var DEFAULT_THEME_NAME="humain-dark",themeJsonValidator;function setThemeJsonValidator(validator){themeJsonValidator=validator}function resolveVarRefs(value,vars,visited=new Set){if(typeof value=="number"||value===""||value.startsWith("#")||/^ok(lch|hsl)\(/i.test(value))return value;if(visited.has(value))throw new Error(`Circular variable reference detected: ${value}`);if(!(value in vars))throw new Error(`Variable reference not found: ${value}`);return visited.add(value),resolveVarRefs(vars[value],
1120
- vars,visited)}function resolveThemeColors(colors,vars={}){let resolved={};for(let[key,value]of Object.entries(colors))resolved[key]=resolveVarRefs(value,vars);return resolved}function withThemeColorFallbacks(colors){return{...colors,scrollbarTrack:colors.scrollbarTrack??colors.muted,scrollbarThumb:colors.scrollbarThumb??colors.text,thinkingMax:colors.thinkingMax??colors.thinkingXhigh,searchMatchBg:colors.searchMatchBg??colors.selectedBg,searchMatchText:colors.searchMatchText??colors.text}}var terminalColors={},
1121
- terminalColorsPending=!1,terminalColorScheme;function setTerminalColors(colors){terminalColors={...colors},terminalColorsPending=!1}function setTerminalColorScheme(scheme){terminalColorScheme=scheme}function markTerminalColorsPending(){terminalColorsPending=!0}var GUESSED_DEFAULT_COLORS={dark:{foreground:parseColor("#e5e5e7"),background:parseColor("#000000")},light:{foreground:parseColor("#000000"),background:parseColor("#ffffff")}};function averageLightness(colors){let fixed=colors.filter(color=>color.
1122
- kind!=="indexed"||color.index>=16);if(fixed.length!==0)return fixed.reduce((sum,color)=>sum+colorToOklch(color).l,0)/fixed.length}function detectAppearance(foregrounds,backgrounds){let fg=averageLightness(foregrounds),bg=averageLightness(backgrounds);if(fg!==void 0&&bg!==void 0)return bg<fg?"dark":"light";if(bg!==void 0)return bg<.5?"dark":"light";if(fg!==void 0)return fg>.5?"dark":"light"}var Theme=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(fgColors,bgColors,mode,options={}){
1123
- this.name=options.name,this.sourcePath=options.sourcePath,this.sourceInfo=options.sourceInfo,this.mode=mode,this.dimTokens=new Set(options.dim);let foregrounds={...fgColors,scrollbarTrack:fgColors.scrollbarTrack??fgColors.muted,scrollbarThumb:fgColors.scrollbarThumb??fgColors.text,thinkingMax:fgColors.thinkingMax??fgColors.thinkingXhigh,searchMatchText:fgColors.searchMatchText??fgColors.text},backgrounds={...bgColors,searchMatchBg:bgColors.searchMatchBg??bgColors.selectedBg},concreteForegrounds=[],
1124
- concreteBackgrounds=[],addToken=(token,value,isBackground)=>{if(value==="")return(isBackground?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(token),isBackground?"\x1B[49m":"\x1B[39m";let color=parseColor(value);return this.concreteColors[token]=color,(isBackground?concreteBackgrounds:concreteForegrounds).push(color),isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode)};for(let[token,value]of Object.entries(foregrounds))this.fgAnsi.set(token,addToken(token,value,!1));
1125
- for(let[token,value]of Object.entries(backgrounds))this.bgAnsi.set(token,addToken(token,value,!0));this.ownAppearance=options.appearance??detectAppearance(concreteForegrounds,concreteBackgrounds)}get appearance(){return this.ownAppearance??getTerminalTheme()}get colors(){let terminal=terminalColors;if(this.resolvedColors?.terminal!==terminal){let guess=GUESSED_DEFAULT_COLORS[this.appearance],toColor=(rgb,fallback)=>rgb?rgbColor(rgb.r,rgb.g,rgb.b):fallback,foreground=toColor(terminal.foreground,guess.
1126
- foreground),background=toColor(terminal.background,guess.background),colors={...this.concreteColors};for(let token of this.defaultForegroundTokens)colors[token]=foreground;for(let token of this.defaultBackgroundTokens)colors[token]=background;for(let token of this.dimTokens){let color=colors[token];color&&(colors[token]=mixColors(color,background,.4))}this.resolvedColors={terminal,colors:Object.freeze(colors)}}return this.resolvedColors.colors}style(text,options){let{fg,bg}=options;return typeof fg==
1127
- "string"&&this.dimTokens.has(fg)&&(options={...options,dim:!0}),styleTextWithAnsi(text,fg===void 0?void 0:typeof fg=="string"?this.tokenAnsi(this.fgAnsi,fg):foregroundAnsi(fg,this.mode),bg===void 0?void 0:typeof bg=="string"?this.tokenAnsi(this.bgAnsi,bg):backgroundAnsi(bg,this.mode),options)}fg(color,text){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m${text}\x1B[22;39m`:`${ansi}${text}\x1B[39m`}bg(color,text){return`${this.tokenAnsi(this.bgAnsi,color)}${text}\
1128
- \x1B[49m`}tokenAnsi(ansi,token){let value=ansi.get(token);if(value===void 0)throw new Error(`Unknown theme color: ${token}`);return value}bold(text){return source_default.bold(text)}italic(text){return source_default.italic(text)}underline(text){return source_default.underline(text)}inverse(text){return source_default.inverse(text)}strikethrough(text){return source_default.strikethrough(text)}getFgAnsi(color){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2\
1129
- m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str=>this.fg("thinkingOff",str);case"minimal":return str=>this.fg("thinkingMinimal",str);case"low":return str=>this.fg("thinkingLow",str);case"medium":return str=>this.fg("thinkingMedium",str);case"high":return str=>this.fg("thinkingHigh",str);case"xhigh":return str=>this.fg("thinkingXhigh",str);case"max":return str=>this.fg("thinkingMax",
1130
- str);default:return str=>this.fg("thinkingOff",str)}}getBashModeBorderColor(){return str=>this.fg("bashMode",str)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json"),humainDarkPath=path4.join(themesDir,"humain-dark.json"),humainLightPath=path4.join(themesDir,"humain-light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(darkPath,"utf-8"))),light:JSON.parse(
1131
- stripBom(fs3.readFileSync(lightPath,"utf-8"))),"humain-dark":JSON.parse(stripBom(fs3.readFileSync(humainDarkPath,"utf-8"))),"humain-light":JSON.parse(stripBom(fs3.readFileSync(humainLightPath,"utf-8")))}}return BUILTIN_THEMES}function getAvailableThemes(){return getAvailableThemesWithPaths().map(({name})=>name)}function getAvailableThemesWithPaths(){let themesDir=getThemesDir(),result=[],seen=new Set,addTheme=themeInfo=>{seen.has(themeInfo.name)||(seen.add(themeInfo.name),result.push(themeInfo))};
1132
- addTheme({name:SYSTEM_THEME_NAME,path:void 0});for(let name of Object.keys(getBuiltinThemes()))addTheme({name,path:path4.join(themesDir,`${name}.json`)});for(let themeInfo of getCustomThemeInfos())addTheme(themeInfo);for(let[name,theme2]of registeredThemes.entries())addTheme({name,path:theme2.sourcePath});return result.sort((a,b)=>a.name===SYSTEM_THEME_NAME?-1:b.name===SYSTEM_THEME_NAME?1:a.name.localeCompare(b.name))}function getCustomThemeInfos(){let customThemesDir=getCustomThemesDir(),result=[];
1133
- if(!fs3.existsSync(customThemesDir))return result;for(let file of fs3.readdirSync(customThemesDir)){if(!file.endsWith(".json"))continue;let themePath=path4.join(customThemesDir,file);try{let customTheme=loadThemeFromPath(themePath);customTheme.name&&result.push({name:customTheme.name,path:themePath})}catch{}}return result}function assertThemeNameIsValid(name){if(name.includes("/"))throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for automatic l\
1134
- ight/dark theme settings.`)}function parseThemeJson(label,json2){if(themeJsonValidator)return themeJsonValidator(label,json2);if(typeof json2!="object"||json2===null||!("colors"in json2))throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);return json2}function parseThemeJsonContent(label,content){let json2;try{json2=JSON.parse(stripBom(content))}catch(error){throw new Error(`Failed to parse theme ${label}: ${error}`)}return parseThemeJson(label,json2)}function loadThemeJson(name){
1108
+ extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfaceL)??extreme)-surfaceL,compressed=Math.abs(distance)>Math.abs(floor)?distance-(distance-floor)*Math.min(t,1):distance;return surfaceL+compressed*(1-Math.max(0,t-1))},extremeText=lighter?{r:255,g:255,b:255}:{r:0,g:0,b:0},readable=color=>wcagContrast(extremeText,color)>=TEXT_MINIMUM_WCAG_CONTRAST,limitPanel=(token,l)=>{let color=paint(token,l);if(readable(color))return color;let[low,high]=[backgroundL,l];for(let index=0;index<
1109
+ 20;index++){let middle=(low+high)/2;readable(paint(token,middle))?low=middle:high=middle}return paint(token,low)},solve=t=>{let colors2=new Map([["background",background]]);for(let token of SOLVE_ORDER){let targets=[];for(let rule of RULES)if(rule.token===token)for(let surface of rule.on){let value=target(rule.level,oklabLightness(colors2.get(surface)??background),t);if(value===void 0||value<0||value>1)return;targets.push(value)}let l=lighter?Math.max(...targets):Math.min(...targets);colors2.set(
1110
+ token,PANELS.includes(token)?limitPanel(token,l):paint(token,l))}return colors2},relaxation=0,colors=solve(0);if(!colors){let[low,high]=[0,2];colors=solve(high);for(let index=0;index<20;index++){let middle=(low+high)/2,attempt=solve(middle);attempt?[high,colors]=[middle,attempt]:low=middle}relaxation=high}let solved=colors??new Map,surfacesOf=token=>RULES.filter(rule=>rule.token===token).flatMap(rule=>rule.on.map(surface=>solved.get(surface)??background)),result={};for(let token of Object.keys(TOKEN_FAMILIES)){
1111
+ let color=solved.get(token);result[token]=color?hexOf(color):""}for(let token of FOREGROUND_TOKENS){let surfaces=surfacesOf(token),text=solved.get(token);if(foreground){let targets=surfaces.map(surface=>target(FOREGROUND_LEVEL,oklabLightness(surface),relaxation));if(targets.every(value=>value!==void 0&&value>=0&&value<=1)){let needed=lighter?Math.max(...targets):Math.min(...targets),foregroundL=oklabLightness(foreground);if(lighter?foregroundL>=needed:foregroundL<=needed){result[token]="";continue}
1112
+ text=anchored(sourceOf(foreground),FAMILIES.neutral,oklabToOkhslLightness(needed),saturation)}}text&&(result[token]=hexOf(withTextContrast(text,surfaces,lighter)))}return{colors:result,dim:[],appearance}}function okhslOf({r,g,b}){return colorToOkhsl(rgbColor(r,g,b))}function sourceOf(color){return{...okhslOf(color),chroma:colorToOklch(rgbColor(color.r,color.g,color.b)).c}}function anchored(source2,family,lightness,saturation){let anchor=saturationCurve(family,source2.l),falloff=anchor>0?Math.min(
1113
+ 1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source2.h,source2.s*falloff*saturation,lightness),cap=source2.chroma*falloff*saturation,{l,c:c2}=colorToOklch(color);return c2<=cap?color:colorToRgb(oklchColor(l,cap,source2.h))}function withTextContrast(color,surfaces,lighter){let meets=candidate=>surfaces.every(surface=>wcagContrast(candidate,surface)>=TEXT_MINIMUM_WCAG_CONTRAST);if(meets(color))return color;let{h:h2,s,l}=okhslOf(color),at2=lightness=>okhslColor(h2,s,lightness),extreme=lighter?
1114
+ 1:0;if(!meets(at2(extreme)))return at2(extreme);let[low,high]=[l,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at2(middle))?high=middle:low=middle}return at2(high)}function indexedColors(saturation,appearance){let colors={},dim=[];for(let[token,familyName]of Object.entries(TOKEN_FAMILIES)){if(PANELS.includes(token)){colors[token]="";continue}let neutral=familyName==="neutral";colors[token]=!neutral&&saturation>0?TOKEN_SLOTS[token]??FAMILIES[familyName].slot:"",neutral&&
1115
+ !FOREGROUND_TOKENS.includes(token)&&dim.push(token)}return{colors,dim,appearance}}function defineThemeTokens(tokens){for(let[name,descriptor]of Object.entries(tokens)){if(descriptor.fallback===void 0)continue;let fallback=tokens[descriptor.fallback];if(fallback===void 0)throw new Error(`Theme token ${name} has unknown fallback ${descriptor.fallback}`);if(fallback.slot!==descriptor.slot)throw new Error(`Theme token ${name} has fallback ${descriptor.fallback} in a different color slot`)}return tokens}var THEME_TOKENS=defineThemeTokens({accent:{slot:"foreground",description:"Pri\
1116
+ mary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"\
1117
+ Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"backgrou\
1118
+ nd",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User messa\
1119
+ ge text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execu\
1120
+ tion box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block cont\
1121
+ ent"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed li\
1122
+ nes in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string lit\
1123
+ erals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{
1124
+ slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash\
1125
+ mode"}});var DEFAULT_THEME_NAME="humain-dark",themeJsonValidator;function setThemeJsonValidator(validator){themeJsonValidator=validator}function resolveVarRefs(value,vars,visited=new Set){if(typeof value=="number"||value===""||value.startsWith("#")||/^ok(lch|hsl)\(/i.test(value))return value;if(visited.has(value))throw new Error(`Circular variable reference detected: ${value}`);if(!(value in vars))throw new Error(`Variable reference not found: ${value}`);return visited.add(value),resolveVarRefs(vars[value],
1126
+ vars,visited)}function resolveThemeColors(colors,vars={}){let resolved={};for(let[key,value]of Object.entries(colors))resolved[key]=resolveVarRefs(value,vars);return resolved}function withThemeTokenFallbacks(values){let resolved={...values};for(let[rawName,descriptor]of Object.entries(THEME_TOKENS)){if(!("fallback"in descriptor))continue;let name=rawName;if(resolved[name]!==void 0)continue;let fallback=descriptor.fallback,fallbackValue=resolved[fallback];if(fallbackValue===void 0)throw new Error(
1127
+ `Theme token ${rawName} has unresolved fallback ${descriptor.fallback}`);resolved[name]=fallbackValue}return resolved}var terminalColors={},terminalColorsPending=!1,terminalColorScheme;function setTerminalColors(colors){terminalColors={...colors},terminalColorsPending=!1}function setTerminalColorScheme(scheme){terminalColorScheme=scheme}function markTerminalColorsPending(){terminalColorsPending=!0}var GUESSED_DEFAULT_COLORS={dark:{foreground:parseColor("#e5e5e7"),background:parseColor("#000000")},
1128
+ light:{foreground:parseColor("#000000"),background:parseColor("#ffffff")}};function averageLightness(colors){let fixed=colors.filter(color=>color.kind!=="indexed"||color.index>=16);if(fixed.length!==0)return fixed.reduce((sum,color)=>sum+colorToOklch(color).l,0)/fixed.length}function detectAppearance(foregrounds,backgrounds){let fg=averageLightness(foregrounds),bg=averageLightness(backgrounds);if(fg!==void 0&&bg!==void 0)return bg<fg?"dark":"light";if(bg!==void 0)return bg<.5?"dark":"light";if(fg!==
1129
+ void 0)return fg>.5?"dark":"light"}var Theme=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(fgColors,bgColors,mode,options={}){this.name=options.name,this.sourcePath=options.sourcePath,this.sourceInfo=options.sourceInfo,this.mode=mode,this.dimTokens=new Set(options.dim);let{fgColors:foregrounds,bgColors:backgrounds}=splitThemeColors(withThemeTokenFallbacks(
1130
+ {...fgColors,...bgColors})),concreteForegrounds=[],concreteBackgrounds=[],addToken=(token,value,isBackground)=>{if(value==="")return(isBackground?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(token),isBackground?"\x1B[49m":"\x1B[39m";let color=parseColor(value);return this.concreteColors[token]=color,(isBackground?concreteBackgrounds:concreteForegrounds).push(color),isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode)};for(let[token,value]of Object.entries(foregrounds))
1131
+ this.fgAnsi.set(token,addToken(token,value,!1));for(let[token,value]of Object.entries(backgrounds))this.bgAnsi.set(token,addToken(token,value,!0));this.ownAppearance=options.appearance??detectAppearance(concreteForegrounds,concreteBackgrounds)}get appearance(){return this.ownAppearance??getTerminalTheme()}get colors(){let terminal=terminalColors;if(this.resolvedColors?.terminal!==terminal){let guess=GUESSED_DEFAULT_COLORS[this.appearance],toColor=(rgb,fallback)=>rgb?rgbColor(rgb.r,rgb.g,rgb.b):fallback,
1132
+ foreground=toColor(terminal.foreground,guess.foreground),background=toColor(terminal.background,guess.background),colors={...this.concreteColors};for(let token of this.defaultForegroundTokens)colors[token]=foreground;for(let token of this.defaultBackgroundTokens)colors[token]=background;for(let token of this.dimTokens){let color=colors[token];color&&(colors[token]=mixColors(color,background,.4))}this.resolvedColors={terminal,colors:Object.freeze(colors)}}return this.resolvedColors.colors}style(text,options){
1133
+ let{fg,bg}=options;return typeof fg=="string"&&this.dimTokens.has(fg)&&(options={...options,dim:!0}),styleTextWithAnsi(text,fg===void 0?void 0:typeof fg=="string"?this.tokenAnsi(this.fgAnsi,fg):foregroundAnsi(fg,this.mode),bg===void 0?void 0:typeof bg=="string"?this.tokenAnsi(this.bgAnsi,bg):backgroundAnsi(bg,this.mode),options)}fg(color,text){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m${text}\x1B[22;39m`:`${ansi}${text}\x1B[39m`}bg(color,text){return`${this.
1134
+ tokenAnsi(this.bgAnsi,color)}${text}\x1B[49m`}tokenAnsi(ansi,token){let value=ansi.get(token);if(value===void 0)throw new Error(`Unknown theme color: ${token}`);return value}bold(text){return source_default.bold(text)}italic(text){return source_default.italic(text)}underline(text){return source_default.underline(text)}inverse(text){return source_default.inverse(text)}strikethrough(text){return source_default.strikethrough(text)}getFgAnsi(color){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.
1135
+ dimTokens.has(color)?`${ansi}\x1B[2m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str=>this.fg("thinkingOff",str);case"minimal":return str=>this.fg("thinkingMinimal",str);case"low":return str=>this.fg("thinkingLow",str);case"medium":return str=>this.fg("thinkingMedium",str);case"high":return str=>this.fg("thinkingHigh",str);case"xhigh":return str=>this.fg("thinkingXhigh",str);case"max":
1136
+ return str=>this.fg("thinkingMax",str);default:return str=>this.fg("thinkingOff",str)}}getBashModeBorderColor(){return str=>this.fg("bashMode",str)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json"),humainDarkPath=path4.join(themesDir,"humain-dark.json"),humainLightPath=path4.join(themesDir,"humain-light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(
1137
+ darkPath,"utf-8"))),light:JSON.parse(stripBom(fs3.readFileSync(lightPath,"utf-8"))),"humain-dark":JSON.parse(stripBom(fs3.readFileSync(humainDarkPath,"utf-8"))),"humain-light":JSON.parse(stripBom(fs3.readFileSync(humainLightPath,"utf-8")))}}return BUILTIN_THEMES}function getAvailableThemes(){return getAvailableThemesWithPaths().map(({name})=>name)}function getAvailableThemesWithPaths(){let themesDir=getThemesDir(),result=[],seen=new Set,addTheme=themeInfo=>{seen.has(themeInfo.name)||(seen.add(themeInfo.
1138
+ name),result.push(themeInfo))};addTheme({name:SYSTEM_THEME_NAME,path:void 0});for(let name of Object.keys(getBuiltinThemes()))addTheme({name,path:path4.join(themesDir,`${name}.json`)});for(let themeInfo of getCustomThemeInfos())addTheme(themeInfo);for(let[name,theme2]of registeredThemes.entries())addTheme({name,path:theme2.sourcePath});return result.sort((a3,b)=>a3.name===SYSTEM_THEME_NAME?-1:b.name===SYSTEM_THEME_NAME?1:a3.name.localeCompare(b.name))}function getCustomThemeInfos(){let customThemesDir=getCustomThemesDir(),
1139
+ result=[];if(!fs3.existsSync(customThemesDir))return result;for(let file of fs3.readdirSync(customThemesDir)){if(!file.endsWith(".json"))continue;let themePath=path4.join(customThemesDir,file);try{let customTheme=loadThemeFromPath(themePath);customTheme.name&&result.push({name:customTheme.name,path:themePath})}catch{}}return result}function assertThemeNameIsValid(name){if(name.includes("/"))throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for a\
1140
+ utomatic light/dark theme settings.`)}function parseThemeJson(label,json2){if(themeJsonValidator)return themeJsonValidator(label,json2);if(typeof json2!="object"||json2===null||!("colors"in json2))throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);return json2}function parseThemeJsonContent(label,content){let json2;try{json2=JSON.parse(stripBom(content))}catch(error){throw new Error(`Failed to parse theme ${label}: ${error}`)}return parseThemeJson(label,json2)}function loadThemeJson(name){
1135
1141
  let builtinThemes=getBuiltinThemes();if(name in builtinThemes)return builtinThemes[name];let registeredTheme=registeredThemes.get(name);if(registeredTheme?.sourcePath){let content2=fs3.readFileSync(registeredTheme.sourcePath,"utf-8");return parseThemeJsonContent(registeredTheme.sourcePath,content2)}if(registeredTheme)throw new Error(`Theme "${name}" does not have a source path for export`);let customThemesDir=getCustomThemesDir(),themePath=path4.join(customThemesDir,`${name}.json`);if(!fs3.existsSync(
1136
- themePath))throw new Error(`Theme not found: ${name}`);let content=fs3.readFileSync(themePath,"utf-8");return parseThemeJsonContent(name,content)}var BACKGROUND_TOKENS=new Set(["selectedBg","searchMatchBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))BACKGROUND_TOKENS.has(key)?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){
1137
- let colorMode=mode??getTerminalColorMode(),resolvedColors=resolveThemeColors(withThemeColorFallbacks(themeJson.colors),themeJson.vars),{fgColors,bgColors}=splitThemeColors(resolvedColors);return new Theme(fgColors,bgColors,colorMode,{name:themeJson.name,sourcePath,appearance:themeJson.appearance})}function createSystemTheme(mode){let generated=generateSystemThemeColors({...terminalColors,saturation:terminalColorsPending?0:1,appearanceHint:getTerminalTheme()}),{fgColors,bgColors}=splitThemeColors(
1138
- generated.colors);return new Theme(fgColors,bgColors,mode??getTerminalColorMode(),{name:SYSTEM_THEME_NAME,appearance:generated.appearance,dim:generated.dim})}function loadThemeFromPath(themePath,mode){let content=fs3.readFileSync(themePath,"utf-8"),themeJson=parseThemeJsonContent(themePath,content);return createTheme(themeJson,mode,themePath)}function loadTheme(name,mode){if(name===SYSTEM_THEME_NAME)return createSystemTheme(mode);let registeredTheme=registeredThemes.get(name);if(registeredTheme)
1139
- return registeredTheme;let themeJson=loadThemeJson(name);return createTheme(themeJson,mode)}function getThemeByName(name){try{return loadTheme(name)}catch{return}}function parseAutoThemeSetting(themeSetting){if(!themeSetting)return;let slashIndex=themeSetting.indexOf("/");if(slashIndex===-1||themeSetting.indexOf("/",slashIndex+1)!==-1)return;let lightTheme=themeSetting.slice(0,slashIndex).trim(),darkTheme=themeSetting.slice(slashIndex+1).trim();if(!(!lightTheme||!darkTheme))return{lightTheme,darkTheme}}
1140
- function resolveThemeSetting(themeSetting,terminalTheme){let autoTheme=parseAutoThemeSetting(themeSetting);if(autoTheme)return terminalTheme==="light"?autoTheme.lightTheme:autoTheme.darkTheme;if(!themeSetting?.includes("/")&&typeof themeSetting=="string")return themeSetting}function detectColorFgBgTheme(env2=process.env){let bg=env2.COLORFGBG?.split(";").at(-1)?.trim();if(!bg||!/^\d{1,2}$/.test(bg))return;let index=Number(bg);if(!(index>15))return index<=6||index===8?"dark":"light"}function detectTerminalTheme(colors={},reportedScheme,env2=process.
1141
- env){let{background,foreground}=colors;return background?terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env2)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("humain-terminal:theme"),THEME_KEY_LEGACY_EARENDIL=Symbol.for("@earendil-works/pi-coding-agent:theme"),THEME_KEY_LEGACY_MARIO=Symbol.for("@mariozechner/pi-coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];
1142
- if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[prop]}});function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_LEGACY_EARENDIL]=t,globalThis[THEME_KEY_LEGACY_MARIO]=t}var currentThemeName,themeWatcher,themeReloadTimer,onThemeChangeCallback,registeredThemes=new Map;function setRegisteredThemes(themes){registeredThemes.clear();for(let theme2 of themes)theme2.name&&(assertThemeNameIsValid(theme2.name),registeredThemes.set(theme2.name,theme2))}function initTheme(themeName,enableWatcher=!1){
1143
- let name=themeName??DEFAULT_THEME_NAME;currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{currentThemeName=SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(SYSTEM_THEME_NAME))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){return currentThemeName=SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(
1144
- SYSTEM_THEME_NAME)),{success:!1,error:error instanceof Error?error.message:String(error)}}}function setThemeInstance(themeInstance){setGlobalTheme(themeInstance),currentThemeName="<in-memory>",stopThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback()}function onThemeChange(callback){onThemeChangeCallback=callback}function startThemeWatcher(){if(stopThemeWatcher(),!currentThemeName||currentThemeName==="dark"||currentThemeName==="light"||currentThemeName===SYSTEM_THEME_NAME)return;let customThemesDir=getCustomThemesDir(),
1145
- watchedThemeName=currentThemeName,watchedFileName=`${watchedThemeName}.json`,themeFile=path4.join(customThemesDir,watchedFileName);if(!fs3.existsSync(themeFile))return;let scheduleReload=()=>{themeReloadTimer&&clearTimeout(themeReloadTimer),themeReloadTimer=setTimeout(()=>{if(themeReloadTimer=void 0,currentThemeName===watchedThemeName&&fs3.existsSync(themeFile))try{let reloadedTheme=loadThemeFromPath(themeFile);registeredThemes.set(watchedThemeName,reloadedTheme),setGlobalTheme(reloadedTheme),onThemeChangeCallback&&
1146
- onThemeChangeCallback()}catch{}},100)};themeWatcher=watchWithErrorHandler(customThemesDir,(_eventType,filename)=>{if(currentThemeName===watchedThemeName){if(!filename){scheduleReload();return}filename===watchedFileName&&scheduleReload()}},()=>{closeWatcher(themeWatcher),themeWatcher=void 0})??void 0}function stopThemeWatcher(){themeReloadTimer&&(clearTimeout(themeReloadTimer),themeReloadTimer=void 0),closeWatcher(themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let colors=loadTheme(
1147
- themeName??currentThemeName??SYSTEM_THEME_NAME).colors;return Object.fromEntries(Object.entries(colors).map(([token,color])=>[token,colorToHex(color)]))}function getThemeExportColors(themeName){let name=themeName??currentThemeName??SYSTEM_THEME_NAME;if(name===SYSTEM_THEME_NAME)return{};try{let themeJson=loadThemeJson(name),exportSection=themeJson.export;if(!exportSection)return{};let vars=themeJson.vars??{},resolve=value=>{if(value===void 0)return;let resolved=resolveVarRefs(value,vars);if(typeof resolved=="number")return colorToHex(indexedColor(resolved));if(resolved!=="")return/^okhsl\(/i.test(resolved)?colorToHex(parseColor(resolved)):resolved};
1142
+ themePath))throw new Error(`Theme not found: ${name}`);let content=fs3.readFileSync(themePath,"utf-8");return parseThemeJsonContent(name,content)}function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))THEME_TOKENS[key].slot==="background"?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){let colorMode=mode??getTerminalColorMode(),resolvedColors=withThemeTokenFallbacks(resolveThemeColors(
1143
+ themeJson.colors,themeJson.vars)),{fgColors,bgColors}=splitThemeColors(resolvedColors);return new Theme(fgColors,bgColors,colorMode,{name:themeJson.name,sourcePath,appearance:themeJson.appearance})}function createSystemTheme(mode){let generated=generateSystemThemeColors({...terminalColors,saturation:terminalColorsPending?0:1,appearanceHint:getTerminalTheme()}),{fgColors,bgColors}=splitThemeColors(withThemeTokenFallbacks(generated.colors));return new Theme(fgColors,bgColors,mode??getTerminalColorMode(),
1144
+ {name:SYSTEM_THEME_NAME,appearance:generated.appearance,dim:generated.dim})}function loadThemeFromPath(themePath,mode){let content=fs3.readFileSync(themePath,"utf-8"),themeJson=parseThemeJsonContent(themePath,content);return createTheme(themeJson,mode,themePath)}function loadTheme(name,mode){if(name===SYSTEM_THEME_NAME)return createSystemTheme(mode);let registeredTheme=registeredThemes.get(name);if(registeredTheme)return registeredTheme;let themeJson=loadThemeJson(name);return createTheme(themeJson,
1145
+ mode)}function getThemeByName(name){try{return loadTheme(name)}catch{return}}function parseAutoThemeSetting(themeSetting){if(!themeSetting)return;let slashIndex=themeSetting.indexOf("/");if(slashIndex===-1||themeSetting.indexOf("/",slashIndex+1)!==-1)return;let lightTheme=themeSetting.slice(0,slashIndex).trim(),darkTheme=themeSetting.slice(slashIndex+1).trim();if(!(!lightTheme||!darkTheme))return{lightTheme,darkTheme}}function resolveThemeSetting(themeSetting,terminalTheme){let autoTheme=parseAutoThemeSetting(
1146
+ themeSetting);if(autoTheme)return terminalTheme==="light"?autoTheme.lightTheme:autoTheme.darkTheme;if(!themeSetting?.includes("/")&&typeof themeSetting=="string")return themeSetting}function detectColorFgBgTheme(env=process.env){let bg=env.COLORFGBG?.split(";").at(-1)?.trim();if(!bg||!/^\d{1,2}$/.test(bg))return;let index=Number(bg);if(!(index>15))return index<=6||index===8?"dark":"light"}function detectTerminalTheme(colors={},reportedScheme,env=process.env){let{background,foreground}=colors;return background?
1147
+ terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("humain-terminal:theme"),THEME_KEY_LEGACY_EARENDIL=Symbol.for("@earendil-works/pi-coding-agent:theme"),THEME_KEY_LEGACY_MARIO=Symbol.for("@mariozechner/pi-coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];if(!t)throw new Error("Theme not initialized. Call\
1148
+ initTheme() first.");return t[prop]}});function getThemeInstance(){return globalThis[THEME_KEY]}function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_LEGACY_EARENDIL]=t,globalThis[THEME_KEY_LEGACY_MARIO]=t}var currentThemeName,themeWatcher,themeReloadTimer,onThemeChangeCallback,registeredThemes=new Map;function setRegisteredThemes(themes){registeredThemes.clear();for(let theme2 of themes)theme2.name&&(assertThemeNameIsValid(theme2.name),registeredThemes.set(theme2.name,theme2))}
1149
+ function initTheme(themeName,enableWatcher=!1){let name=themeName??DEFAULT_THEME_NAME;currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{currentThemeName=SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(SYSTEM_THEME_NAME))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){return currentThemeName=
1150
+ SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(SYSTEM_THEME_NAME)),{success:!1,error:error instanceof Error?error.message:String(error)}}}function setThemeInstance(themeInstance){setGlobalTheme(themeInstance),currentThemeName="<in-memory>",stopThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback()}function onThemeChange(callback){onThemeChangeCallback=callback}function startThemeWatcher(){if(stopThemeWatcher(),!currentThemeName||currentThemeName==="dark"||currentThemeName==="light"||currentThemeName===
1151
+ SYSTEM_THEME_NAME)return;let customThemesDir=getCustomThemesDir(),watchedThemeName=currentThemeName,watchedFileName=`${watchedThemeName}.json`,themeFile=path4.join(customThemesDir,watchedFileName);if(!fs3.existsSync(themeFile))return;let scheduleReload=()=>{themeReloadTimer&&clearTimeout(themeReloadTimer),themeReloadTimer=setTimeout(()=>{if(themeReloadTimer=void 0,currentThemeName===watchedThemeName&&fs3.existsSync(themeFile))try{let reloadedTheme=loadThemeFromPath(themeFile);registeredThemes.set(
1152
+ watchedThemeName,reloadedTheme),setGlobalTheme(reloadedTheme),onThemeChangeCallback&&onThemeChangeCallback()}catch{}},100)};themeWatcher=watchWithErrorHandler(customThemesDir,(_eventType,filename)=>{if(currentThemeName===watchedThemeName){if(!filename){scheduleReload();return}filename===watchedFileName&&scheduleReload()}},()=>{closeWatcher(themeWatcher),themeWatcher=void 0})??void 0}function stopThemeWatcher(){themeReloadTimer&&(clearTimeout(themeReloadTimer),themeReloadTimer=void 0),closeWatcher(
1153
+ themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let colors=loadTheme(themeName??currentThemeName??SYSTEM_THEME_NAME).colors;return Object.fromEntries(Object.entries(colors).map(([token,color])=>[token,colorToHex(color)]))}function getThemeExportColors(themeName){let name=themeName??currentThemeName??SYSTEM_THEME_NAME;if(name===SYSTEM_THEME_NAME)return{};try{let themeJson=loadThemeJson(name),exportSection=themeJson.export;if(!exportSection)return{};let vars=themeJson.vars??{},resolve=value=>{if(value===void 0)return;let resolved=resolveVarRefs(value,vars);if(typeof resolved=="number")return colorToHex(indexedColor(resolved));if(resolved!=="")return/^okhsl\(/i.test(resolved)?colorToHex(parseColor(resolved)):resolved};
1148
1154
  return{pageBg:resolve(exportSection.pageBg),cardBg:resolve(exportSection.cardBg),infoBg:resolve(exportSection.infoBg)}}catch{return{}}}var cachedHighlightThemeFor,cachedCliHighlightTheme;function buildCliHighlightTheme(t){return{keyword:s=>t.fg("syntaxKeyword",s),built_in:s=>t.fg("syntaxType",s),literal:s=>t.fg("syntaxNumber",s),number:s=>t.fg("syntaxNumber",s),regexp:s=>t.fg("syntaxString",s),string:s=>t.fg("syntaxString",s),subst:s=>t.fg("text",s),comment:s=>t.fg("syntaxComment",s),doctag:s=>t.
1149
1155
  fg("syntaxComment",s),meta:s=>t.fg("muted",s),function:s=>t.fg("syntaxFunction",s),title:s=>t.fg("syntaxFunction",s),class:s=>t.fg("syntaxType",s),type:s=>t.fg("syntaxType",s),tag:s=>t.fg("syntaxPunctuation",s),name:s=>t.fg("syntaxKeyword",s),attr:s=>t.fg("syntaxVariable",s),variable:s=>t.fg("syntaxVariable",s),params:s=>t.fg("syntaxVariable",s),operator:s=>t.fg("syntaxOperator",s),punctuation:s=>t.fg("syntaxPunctuation",s),emphasis:s=>t.italic(s),strong:s=>t.bold(s),link:s=>t.underline(s),addition:s=>t.
1150
1156
  fg("toolDiffAdded",s),deletion:s=>t.fg("toolDiffRemoved",s)}}function getCliHighlightTheme(t){return(cachedHighlightThemeFor!==t||!cachedCliHighlightTheme)&&(cachedHighlightThemeFor=t,cachedCliHighlightTheme=buildCliHighlightTheme(t)),cachedCliHighlightTheme}function highlightCode(code,lang){let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
@@ -1157,7 +1163,7 @@ void 0;if(!validLang)return code.split(`
1157
1163
  `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
1158
1164
  `)}catch{return code.split(`
1159
1165
  `).map(line=>theme.fg("mdCodeBlock",line))}}}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.fg("borderMuted",text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,
1160
- value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k2=>k2.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(
1161
- getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{F,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,styleText,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,
1162
- Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,source_default,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,DEFAULT_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,
1163
- getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};
1166
+ value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(
1167
+ getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{U,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,styleText,Key,matchesKey,onCapabilitiesChange,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,markStableRender,renderSharedLines,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,
1168
+ Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguagesOnDemand,SYSTEM_THEME_NAME,THEME_TOKENS,DEFAULT_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,
1169
+ loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,getThemeInstance,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};