@draht/coding-agent 2026.10.31 → 2026.11.5-1

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 (512) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/bundle/chunks/anthropic-messages-UJZ4SGHU.js +6 -0
  3. package/dist/bundle/chunks/azure-openai-responses-NCMJPZVJ.js +2 -0
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +27 -24
  5. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  6. package/dist/bundle/chunks/chunk-3BJ462DN.js +132 -0
  7. package/dist/bundle/chunks/chunk-5OXIAQP5.js +2 -0
  8. package/dist/bundle/chunks/chunk-6M3D4XVD.js +2 -0
  9. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-6WESOD4H.js} +1 -1
  10. package/dist/bundle/chunks/chunk-AOCWORXE.js +2 -0
  11. package/dist/bundle/chunks/chunk-BK5LXGIH.js +2 -0
  12. package/dist/bundle/chunks/chunk-CA23BDNK.js +2 -0
  13. package/dist/bundle/chunks/chunk-DWOGGNWY.js +18 -0
  14. package/dist/bundle/chunks/{chunk-RMLEJL4F.js → chunk-EOXOMUKR.js} +1 -1
  15. package/dist/bundle/chunks/chunk-F5TDVH26.js +159 -0
  16. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  17. package/dist/bundle/chunks/{chunk-ITP6IDBA.js → chunk-GQXRTK54.js} +2 -2
  18. package/dist/bundle/chunks/chunk-HJ3PS7QP.js +4 -0
  19. package/dist/bundle/chunks/chunk-ITKDPD4D.js +12 -0
  20. package/dist/bundle/chunks/chunk-KFREX3FS.js +10 -0
  21. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  22. package/dist/bundle/chunks/{chunk-AACPRSR2.js → chunk-P7O36UDU.js} +2 -2
  23. package/dist/bundle/chunks/chunk-PMINB7UH.js +1401 -0
  24. package/dist/bundle/chunks/chunk-PZKD35UB.js +2 -0
  25. package/dist/bundle/chunks/{chunk-JQF3BGRS.js → chunk-Q2QKCYPU.js} +1 -1
  26. package/dist/bundle/chunks/chunk-QBUTRTYN.js +2 -0
  27. package/dist/bundle/chunks/chunk-SUVMF4W5.js +2 -0
  28. package/dist/bundle/chunks/chunk-UFACUBF2.js +16 -0
  29. package/dist/bundle/chunks/chunk-VXO6B72D.js +9 -0
  30. package/dist/bundle/chunks/{chunk-NUUJKLOX.js → chunk-WXASQQBZ.js} +9 -9
  31. package/dist/bundle/chunks/chunk-Y3NLUJYO.js +2 -0
  32. package/dist/bundle/chunks/chunk-Y7QE2R34.js +2 -0
  33. package/dist/bundle/chunks/chunk-YD5VPPI4.js +30 -0
  34. package/dist/bundle/chunks/chunk-YWRWN7ZB.js +82 -0
  35. package/dist/bundle/chunks/{cli-LGOE6EXL.js → cli-4SUT6MJ6.js} +10 -10
  36. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-BJVMNETD.js +2 -0
  37. package/dist/bundle/chunks/{execute-ZVQ7ITER.js → execute-ZI7T2SUH.js} +1 -1
  38. package/dist/bundle/chunks/github-copilot.js +1 -1
  39. package/dist/bundle/chunks/{google-generative-ai-IHELIMAC.js → google-generative-ai-N5IPPKQY.js} +1 -1
  40. package/dist/bundle/chunks/{google-vertex-3QCFWSNG.js → google-vertex-A4BKUE4H.js} +1 -1
  41. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  42. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  43. package/dist/bundle/chunks/kimi-coding.js +1 -1
  44. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  45. package/dist/bundle/chunks/{llama-cpp-classify-6J5XKC7Q.js → llama-cpp-classify-L4URPZ4F.js} +1 -1
  46. package/dist/bundle/chunks/meta.js +1 -1
  47. package/dist/bundle/chunks/mistral-conversations-CK2BS74V.js +5 -0
  48. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  49. package/dist/bundle/chunks/{node-BZAVEWJ3.js → node-DXZFQBEO.js} +1 -1
  50. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-LBZLUIBE.js} +1 -1
  51. package/dist/bundle/chunks/openai-codex-responses-XGVNKP4D.js +10 -0
  52. package/dist/bundle/chunks/openai-completions-72XZO4Q3.js +7 -0
  53. package/dist/bundle/chunks/{openai-decisions-NDYRKL2E.js → openai-decisions-P5OCXLLD.js} +1 -1
  54. package/dist/bundle/chunks/openai-responses-RGLZ4E3Q.js +4 -0
  55. package/dist/bundle/chunks/{openrouter-images-ZIDF5HXA.js → openrouter-images-LSBWMZDK.js} +1 -1
  56. package/dist/bundle/chunks/pi-messages-CL4MEVNS.js +8 -0
  57. package/dist/bundle/chunks/radius.js +1 -1
  58. package/dist/bundle/chunks/{runtime-MZVF4MP6.js → runtime-F4362CZF.js} +1 -1
  59. package/dist/bundle/chunks/{runtime-7BIFTREJ.js → runtime-FJYRBK3O.js} +1 -1
  60. package/dist/bundle/chunks/settings-manager-T6G6KKY3.js +2 -0
  61. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  62. package/dist/bundle/chunks/typesafe-system-one-BFYS6AEA.js +2 -0
  63. package/dist/bundle/chunks/virtual-modules-BPZIVXNK.js +2 -0
  64. package/dist/bundle/cli-runtime.js +1 -1
  65. package/dist/bundle/index.js +1 -1
  66. package/dist/bundle/rpc-entry.js +1 -1
  67. package/dist/cli/args.d.ts.map +1 -1
  68. package/dist/cli/args.js +8 -7
  69. package/dist/cli/args.js.map +1 -1
  70. package/dist/cli/config-selector.d.ts.map +1 -1
  71. package/dist/cli/config-selector.js +3 -1
  72. package/dist/cli/config-selector.js.map +1 -1
  73. package/dist/config.d.ts +10 -0
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +24 -5
  76. package/dist/config.js.map +1 -1
  77. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  78. package/dist/core/agent-session-runtime.js +4 -3
  79. package/dist/core/agent-session-runtime.js.map +1 -1
  80. package/dist/core/agent-session.d.ts +16 -1
  81. package/dist/core/agent-session.d.ts.map +1 -1
  82. package/dist/core/agent-session.js +104 -30
  83. package/dist/core/agent-session.js.map +1 -1
  84. package/dist/core/ai-schemas.d.ts +166 -0
  85. package/dist/core/ai-schemas.d.ts.map +1 -0
  86. package/dist/core/ai-schemas.js +21 -0
  87. package/dist/core/ai-schemas.js.map +1 -0
  88. package/dist/core/auth-storage.d.ts.map +1 -1
  89. package/dist/core/auth-storage.js +3 -2
  90. package/dist/core/auth-storage.js.map +1 -1
  91. package/dist/core/bash-executor.d.ts.map +1 -1
  92. package/dist/core/bash-executor.js +3 -1
  93. package/dist/core/bash-executor.js.map +1 -1
  94. package/dist/core/bug-report.d.ts +4 -4
  95. package/dist/core/cache-warmer.d.ts.map +1 -1
  96. package/dist/core/cache-warmer.js +2 -0
  97. package/dist/core/cache-warmer.js.map +1 -1
  98. package/dist/core/compaction/branch-summarization.d.ts +4 -2
  99. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  100. package/dist/core/compaction/branch-summarization.js +16 -4
  101. package/dist/core/compaction/branch-summarization.js.map +1 -1
  102. package/dist/core/exec.d.ts +9 -1
  103. package/dist/core/exec.d.ts.map +1 -1
  104. package/dist/core/exec.js +104 -60
  105. package/dist/core/exec.js.map +1 -1
  106. package/dist/core/export-html/template.css +9 -0
  107. package/dist/core/export-html/template.js +165 -45
  108. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  109. package/dist/core/export-html/tool-renderer.js +3 -0
  110. package/dist/core/export-html/tool-renderer.js.map +1 -1
  111. package/dist/core/extensions/ai-extension-view.d.ts +19 -0
  112. package/dist/core/extensions/ai-extension-view.d.ts.map +1 -0
  113. package/dist/core/extensions/ai-extension-view.js +22 -0
  114. package/dist/core/extensions/ai-extension-view.js.map +1 -0
  115. package/dist/core/extensions/index.d.ts +1 -1
  116. package/dist/core/extensions/index.d.ts.map +1 -1
  117. package/dist/core/extensions/index.js.map +1 -1
  118. package/dist/core/extensions/loader.d.ts.map +1 -1
  119. package/dist/core/extensions/loader.js +15 -9
  120. package/dist/core/extensions/loader.js.map +1 -1
  121. package/dist/core/extensions/runner.d.ts +1 -0
  122. package/dist/core/extensions/runner.d.ts.map +1 -1
  123. package/dist/core/extensions/runner.js +9 -1
  124. package/dist/core/extensions/runner.js.map +1 -1
  125. package/dist/core/extensions/types.d.ts +55 -11
  126. package/dist/core/extensions/types.d.ts.map +1 -1
  127. package/dist/core/extensions/types.js.map +1 -1
  128. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  129. package/dist/core/extensions/virtual-modules.js +6 -5
  130. package/dist/core/extensions/virtual-modules.js.map +1 -1
  131. package/dist/core/keybindings.d.ts +2 -2
  132. package/dist/core/keybindings.js +1 -1
  133. package/dist/core/keybindings.js.map +1 -1
  134. package/dist/core/mcp-servers.d.ts +21 -38
  135. package/dist/core/mcp-servers.d.ts.map +1 -1
  136. package/dist/core/mcp-servers.js +58 -134
  137. package/dist/core/mcp-servers.js.map +1 -1
  138. package/dist/core/model-config.d.ts +1717 -1990
  139. package/dist/core/model-config.d.ts.map +1 -1
  140. package/dist/core/model-config.js +2 -3
  141. package/dist/core/model-config.js.map +1 -1
  142. package/dist/core/model-resolver.d.ts.map +1 -1
  143. package/dist/core/model-resolver.js +16 -9
  144. package/dist/core/model-resolver.js.map +1 -1
  145. package/dist/core/model-runtime.d.ts.map +1 -1
  146. package/dist/core/model-runtime.js +4 -4
  147. package/dist/core/model-runtime.js.map +1 -1
  148. package/dist/core/package-manager.d.ts +24 -1
  149. package/dist/core/package-manager.d.ts.map +1 -1
  150. package/dist/core/package-manager.js +215 -52
  151. package/dist/core/package-manager.js.map +1 -1
  152. package/dist/core/pi-manifest.d.ts +1 -0
  153. package/dist/core/pi-manifest.d.ts.map +1 -1
  154. package/dist/core/pi-manifest.js +3 -0
  155. package/dist/core/pi-manifest.js.map +1 -1
  156. package/dist/core/project-trust.js +1 -1
  157. package/dist/core/project-trust.js.map +1 -1
  158. package/dist/core/provider-composer.d.ts +2 -1
  159. package/dist/core/provider-composer.d.ts.map +1 -1
  160. package/dist/core/provider-composer.js +8 -4
  161. package/dist/core/provider-composer.js.map +1 -1
  162. package/dist/core/resource-loader.d.ts +4 -1
  163. package/dist/core/resource-loader.d.ts.map +1 -1
  164. package/dist/core/resource-loader.js +38 -23
  165. package/dist/core/resource-loader.js.map +1 -1
  166. package/dist/core/sdk.d.ts.map +1 -1
  167. package/dist/core/sdk.js +3 -1
  168. package/dist/core/sdk.js.map +1 -1
  169. package/dist/core/session-manager.d.ts +7 -0
  170. package/dist/core/session-manager.d.ts.map +1 -1
  171. package/dist/core/session-manager.js +32 -13
  172. package/dist/core/session-manager.js.map +1 -1
  173. package/dist/core/settings-manager.d.ts +2 -0
  174. package/dist/core/settings-manager.d.ts.map +1 -1
  175. package/dist/core/settings-manager.js +11 -0
  176. package/dist/core/settings-manager.js.map +1 -1
  177. package/dist/core/settings-schema.d.ts +4 -2
  178. package/dist/core/settings-schema.d.ts.map +1 -1
  179. package/dist/core/settings-schema.js +8 -1
  180. package/dist/core/settings-schema.js.map +1 -1
  181. package/dist/core/skills.d.ts.map +1 -1
  182. package/dist/core/skills.js +6 -15
  183. package/dist/core/skills.js.map +1 -1
  184. package/dist/core/slash-commands.js +2 -2
  185. package/dist/core/slash-commands.js.map +1 -1
  186. package/dist/core/source-info.d.ts +9 -0
  187. package/dist/core/source-info.d.ts.map +1 -1
  188. package/dist/core/source-info.js +14 -0
  189. package/dist/core/source-info.js.map +1 -1
  190. package/dist/core/system-prompt.d.ts.map +1 -1
  191. package/dist/core/system-prompt.js +5 -6
  192. package/dist/core/system-prompt.js.map +1 -1
  193. package/dist/core/tools/bash.d.ts +2 -2
  194. package/dist/core/tools/bash.d.ts.map +1 -1
  195. package/dist/core/tools/bash.js.map +1 -1
  196. package/dist/core/tools/edit.d.ts +3 -3
  197. package/dist/core/tools/edit.d.ts.map +1 -1
  198. package/dist/core/tools/edit.js +2 -4
  199. package/dist/core/tools/edit.js.map +1 -1
  200. package/dist/core/tools/find.d.ts +2 -2
  201. package/dist/core/tools/find.d.ts.map +1 -1
  202. package/dist/core/tools/find.js +41 -25
  203. package/dist/core/tools/find.js.map +1 -1
  204. package/dist/core/tools/grep.d.ts +4 -5
  205. package/dist/core/tools/grep.d.ts.map +1 -1
  206. package/dist/core/tools/grep.js +73 -70
  207. package/dist/core/tools/grep.js.map +1 -1
  208. package/dist/core/tools/ls.d.ts +2 -2
  209. package/dist/core/tools/ls.d.ts.map +1 -1
  210. package/dist/core/tools/ls.js +2 -1
  211. package/dist/core/tools/ls.js.map +1 -1
  212. package/dist/core/tools/read.d.ts +2 -2
  213. package/dist/core/tools/read.d.ts.map +1 -1
  214. package/dist/core/tools/read.js.map +1 -1
  215. package/dist/core/tools/render-utils.d.ts.map +1 -1
  216. package/dist/core/tools/render-utils.js +2 -7
  217. package/dist/core/tools/render-utils.js.map +1 -1
  218. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  219. package/dist/core/tools/renderers/write.js +19 -19
  220. package/dist/core/tools/renderers/write.js.map +1 -1
  221. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  222. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  223. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  224. package/dist/core/tools/truncate.d.ts +0 -14
  225. package/dist/core/tools/truncate.d.ts.map +1 -1
  226. package/dist/core/tools/truncate.js +0 -29
  227. package/dist/core/tools/truncate.js.map +1 -1
  228. package/dist/core/tools/write.d.ts +2 -2
  229. package/dist/core/tools/write.d.ts.map +1 -1
  230. package/dist/core/tools/write.js.map +1 -1
  231. package/dist/core/trust-manager.d.ts.map +1 -1
  232. package/dist/core/trust-manager.js +15 -8
  233. package/dist/core/trust-manager.js.map +1 -1
  234. package/dist/core/usage-totals.d.ts.map +1 -1
  235. package/dist/core/usage-totals.js +2 -0
  236. package/dist/core/usage-totals.js.map +1 -1
  237. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  238. package/dist/extensions/codemode/renderer.js +6 -2
  239. package/dist/extensions/codemode/renderer.js.map +1 -1
  240. package/dist/extensions/codemode/tool.d.ts +2 -1
  241. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  242. package/dist/extensions/codemode/tool.js +33 -8
  243. package/dist/extensions/codemode/tool.js.map +1 -1
  244. package/dist/extensions/llama/client.d.ts +2 -0
  245. package/dist/extensions/llama/client.d.ts.map +1 -1
  246. package/dist/extensions/llama/client.js +23 -2
  247. package/dist/extensions/llama/client.js.map +1 -1
  248. package/dist/extensions/llama/ui.d.ts.map +1 -1
  249. package/dist/extensions/llama/ui.js +16 -4
  250. package/dist/extensions/llama/ui.js.map +1 -1
  251. package/dist/extensions/mcp/cli.d.ts +2 -0
  252. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  253. package/dist/extensions/mcp/cli.js +72 -15
  254. package/dist/extensions/mcp/cli.js.map +1 -1
  255. package/dist/extensions/mcp/config.d.ts.map +1 -1
  256. package/dist/extensions/mcp/config.js +4 -7
  257. package/dist/extensions/mcp/config.js.map +1 -1
  258. package/dist/extensions/mcp/index.d.ts.map +1 -1
  259. package/dist/extensions/mcp/index.js +2 -2
  260. package/dist/extensions/mcp/index.js.map +1 -1
  261. package/dist/extensions/mcp/oauth.d.ts +13 -50
  262. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  263. package/dist/extensions/mcp/oauth.js +53 -319
  264. package/dist/extensions/mcp/oauth.js.map +1 -1
  265. package/dist/extensions/mcp/resources.d.ts +1 -1
  266. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  267. package/dist/extensions/mcp/resources.js +4 -3
  268. package/dist/extensions/mcp/resources.js.map +1 -1
  269. package/dist/extensions/mcp/runtime.d.ts +4 -3
  270. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  271. package/dist/extensions/mcp/runtime.js +4 -3
  272. package/dist/extensions/mcp/runtime.js.map +1 -1
  273. package/dist/extensions/mcp/tools.d.ts +2 -23
  274. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  275. package/dist/extensions/mcp/tools.js +6 -58
  276. package/dist/extensions/mcp/tools.js.map +1 -1
  277. package/dist/extensions/mcp/ui.d.ts +1 -0
  278. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  279. package/dist/extensions/mcp/ui.js +33 -24
  280. package/dist/extensions/mcp/ui.js.map +1 -1
  281. package/dist/extensions/tool-search/tool.d.ts +21 -6
  282. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  283. package/dist/extensions/tool-search/tool.js +104 -36
  284. package/dist/extensions/tool-search/tool.js.map +1 -1
  285. package/dist/index.d.ts +2 -2
  286. package/dist/index.d.ts.map +1 -1
  287. package/dist/index.js.map +1 -1
  288. package/dist/main.d.ts.map +1 -1
  289. package/dist/main.js +16 -8
  290. package/dist/main.js.map +1 -1
  291. package/dist/modes/interactive/components/assistant-message.d.ts +4 -1
  292. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/assistant-message.js +44 -20
  294. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  295. package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
  296. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  297. package/dist/modes/interactive/components/branch-summary-message.js +12 -4
  298. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  299. package/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
  300. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  301. package/dist/modes/interactive/components/compaction-summary-message.js +12 -4
  302. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  303. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  304. package/dist/modes/interactive/components/config-selector.js +4 -18
  305. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  306. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  307. package/dist/modes/interactive/components/custom-editor.js +7 -0
  308. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  309. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  310. package/dist/modes/interactive/components/custom-entry.js +2 -1
  311. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  312. package/dist/modes/interactive/components/custom-message.d.ts +5 -2
  313. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  314. package/dist/modes/interactive/components/custom-message.js +12 -4
  315. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  316. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  317. package/dist/modes/interactive/components/diff.js +11 -5
  318. package/dist/modes/interactive/components/diff.js.map +1 -1
  319. package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
  320. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  321. package/dist/modes/interactive/components/extension-editor.js +4 -0
  322. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  323. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  324. package/dist/modes/interactive/components/extension-selector.js +9 -1
  325. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  326. package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
  327. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  328. package/dist/modes/interactive/components/login-dialog.js +104 -10
  329. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  330. package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
  331. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
  332. package/dist/modes/interactive/components/markdown-transform.js +3 -2
  333. package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
  334. package/dist/modes/interactive/components/mermaid.d.ts +2 -1
  335. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  336. package/dist/modes/interactive/components/mermaid.js +25 -20
  337. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  338. package/dist/modes/interactive/components/model-selector.d.ts +1 -0
  339. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  340. package/dist/modes/interactive/components/model-selector.js +17 -6
  341. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  342. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
  343. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  344. package/dist/modes/interactive/components/oauth-selector.js +13 -4
  345. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  346. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
  347. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  348. package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
  349. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  350. package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
  351. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  352. package/dist/modes/interactive/components/session-selector-search.js +86 -22
  353. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  354. package/dist/modes/interactive/components/session-selector.d.ts +2 -1
  355. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/session-selector.js +20 -27
  357. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  358. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  359. package/dist/modes/interactive/components/settings-submenu.js +2 -0
  360. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  361. package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
  362. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  363. package/dist/modes/interactive/components/skill-invocation-message.js +12 -4
  364. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  365. package/dist/modes/interactive/components/tool-execution.d.ts +6 -0
  366. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  367. package/dist/modes/interactive/components/tool-execution.js +14 -2
  368. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  369. package/dist/modes/interactive/components/tree-selector.d.ts +2 -0
  370. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  371. package/dist/modes/interactive/components/tree-selector.js +24 -16
  372. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  373. package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
  374. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  375. package/dist/modes/interactive/components/user-message-selector.js +9 -1
  376. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  377. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  378. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  379. package/dist/modes/interactive/components/user-message.js +6 -2
  380. package/dist/modes/interactive/components/user-message.js.map +1 -1
  381. package/dist/modes/interactive/external-editor.d.ts +1 -0
  382. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  383. package/dist/modes/interactive/external-editor.js +16 -4
  384. package/dist/modes/interactive/external-editor.js.map +1 -1
  385. package/dist/modes/interactive/interactive-mode.d.ts +7 -0
  386. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  387. package/dist/modes/interactive/interactive-mode.js +179 -53
  388. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  389. package/dist/modes/interactive/model-search.d.ts +10 -0
  390. package/dist/modes/interactive/model-search.d.ts.map +1 -1
  391. package/dist/modes/interactive/model-search.js +21 -0
  392. package/dist/modes/interactive/model-search.js.map +1 -1
  393. package/dist/modes/interactive/theme/theme.d.ts +10 -0
  394. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  395. package/dist/modes/interactive/theme/theme.js +35 -23
  396. package/dist/modes/interactive/theme/theme.js.map +1 -1
  397. package/dist/modes/print-mode.d.ts.map +1 -1
  398. package/dist/modes/print-mode.js +19 -10
  399. package/dist/modes/print-mode.js.map +1 -1
  400. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  401. package/dist/modes/rpc/rpc-mode.js +53 -23
  402. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  403. package/dist/package-manager-cli.d.ts.map +1 -1
  404. package/dist/package-manager-cli.js +78 -9
  405. package/dist/package-manager-cli.js.map +1 -1
  406. package/dist/utils/ansi.d.ts.map +1 -1
  407. package/dist/utils/ansi.js +5 -2
  408. package/dist/utils/ansi.js.map +1 -1
  409. package/dist/utils/changelog.d.ts +2 -2
  410. package/dist/utils/changelog.d.ts.map +1 -1
  411. package/dist/utils/changelog.js +15 -2
  412. package/dist/utils/changelog.js.map +1 -1
  413. package/dist/utils/clipboard-command.d.ts.map +1 -1
  414. package/dist/utils/clipboard-command.js +4 -0
  415. package/dist/utils/clipboard-command.js.map +1 -1
  416. package/dist/utils/git.d.ts +1 -1
  417. package/dist/utils/git.d.ts.map +1 -1
  418. package/dist/utils/git.js.map +1 -1
  419. package/dist/utils/image-resize-core.d.ts.map +1 -1
  420. package/dist/utils/image-resize-core.js +5 -3
  421. package/dist/utils/image-resize-core.js.map +1 -1
  422. package/dist/utils/open-browser.d.ts.map +1 -1
  423. package/dist/utils/open-browser.js +4 -1
  424. package/dist/utils/open-browser.js.map +1 -1
  425. package/dist/utils/paths.d.ts +17 -0
  426. package/dist/utils/paths.d.ts.map +1 -1
  427. package/dist/utils/paths.js +42 -1
  428. package/dist/utils/paths.js.map +1 -1
  429. package/dist/utils/shell.d.ts.map +1 -1
  430. package/dist/utils/shell.js +14 -0
  431. package/dist/utils/shell.js.map +1 -1
  432. package/dist/utils/syntax-highlight.d.ts +5 -0
  433. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  434. package/dist/utils/syntax-highlight.js +7 -0
  435. package/dist/utils/syntax-highlight.js.map +1 -1
  436. package/dist/utils/tools-manager.d.ts.map +1 -1
  437. package/dist/utils/tools-manager.js +30 -35
  438. package/dist/utils/tools-manager.js.map +1 -1
  439. package/docs/cli.md +22 -10
  440. package/docs/custom-provider.md +2 -0
  441. package/docs/environment-variables.md +2 -0
  442. package/docs/extensions.md +3201 -233
  443. package/docs/keybindings.md +2 -2
  444. package/docs/llama-cpp.md +23 -15
  445. package/docs/message-types.md +1 -1
  446. package/docs/models-configuration.md +17 -4
  447. package/docs/models.md +9 -4
  448. package/docs/packages.md +24 -0
  449. package/docs/providers.md +1 -1
  450. package/docs/rpc.md +3 -1
  451. package/docs/sessions.md +11 -3
  452. package/docs/settings.md +5 -4
  453. package/docs/slash-commands.md +3 -2
  454. package/docs/terminal-setup.md +3 -1
  455. package/docs/tmux.md +6 -0
  456. package/docs/tui.md +2 -0
  457. package/docs/windows.md +27 -0
  458. package/eval/drahtbank/isolated-tools.ts +0 -1
  459. package/examples/extensions/antigravity-image-gen.ts +1 -1
  460. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  461. package/examples/extensions/debug-provider.ts +2 -2
  462. package/examples/extensions/gondolin/package.json +1 -1
  463. package/examples/extensions/plan-mode/index.ts +23 -13
  464. package/examples/extensions/plan-mode/utils.ts +42 -16
  465. package/examples/extensions/preset.ts +2 -0
  466. package/examples/extensions/reload-runtime.ts +17 -5
  467. package/examples/extensions/sandbox/package-lock.json +15 -41
  468. package/examples/extensions/sandbox/package.json +1 -1
  469. package/examples/extensions/subagent/index.ts +388 -171
  470. package/examples/extensions/todo.ts +7 -0
  471. package/examples/extensions/tools.ts +2 -0
  472. package/examples/tsconfig.json +188 -0
  473. package/package.json +15 -16
  474. package/schemas/models.schema.json +85 -39
  475. package/schemas/settings.schema.json +17 -0
  476. package/dist/bundle/chunks/anthropic-messages-OR5LCIS6.js +0 -6
  477. package/dist/bundle/chunks/azure-openai-responses-D6DVM232.js +0 -2
  478. package/dist/bundle/chunks/chunk-2MJ6J5N2.js +0 -6
  479. package/dist/bundle/chunks/chunk-2RI4GIFP.js +0 -166
  480. package/dist/bundle/chunks/chunk-57PET6SW.js +0 -82
  481. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  482. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  483. package/dist/bundle/chunks/chunk-76YNMQ57.js +0 -2
  484. package/dist/bundle/chunks/chunk-7JJWQ53O.js +0 -1428
  485. package/dist/bundle/chunks/chunk-AEG546ID.js +0 -16
  486. package/dist/bundle/chunks/chunk-CKPJSVRD.js +0 -2
  487. package/dist/bundle/chunks/chunk-CMKX4CSI.js +0 -6
  488. package/dist/bundle/chunks/chunk-DLEJ4D4T.js +0 -2
  489. package/dist/bundle/chunks/chunk-FXCTQRNN.js +0 -2
  490. package/dist/bundle/chunks/chunk-KINQOWAP.js +0 -4
  491. package/dist/bundle/chunks/chunk-LK54N67E.js +0 -7
  492. package/dist/bundle/chunks/chunk-QJADVGUY.js +0 -2
  493. package/dist/bundle/chunks/chunk-QMN7OD6G.js +0 -2
  494. package/dist/bundle/chunks/chunk-SYRVFGYE.js +0 -2
  495. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  496. package/dist/bundle/chunks/chunk-X4UBYFTC.js +0 -11
  497. package/dist/bundle/chunks/chunk-XB4F3WGD.js +0 -132
  498. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +0 -2
  499. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-YVG4FYXV.js +0 -2
  500. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  501. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  502. package/dist/bundle/chunks/mistral-conversations-D3JRG6BL.js +0 -5
  503. package/dist/bundle/chunks/openai-codex-responses-CBOPSGUQ.js +0 -10
  504. package/dist/bundle/chunks/openai-completions-LDMDMEF2.js +0 -7
  505. package/dist/bundle/chunks/openai-responses-EZWJOXWT.js +0 -4
  506. package/dist/bundle/chunks/pi-messages-R75QWB4G.js +0 -8
  507. package/dist/bundle/chunks/settings-manager-QF6DRH5C.js +0 -2
  508. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  509. package/dist/bundle/chunks/typesafe-system-one-YUNLPYVG.js +0 -2
  510. package/dist/bundle/chunks/virtual-modules-4DJB4LTP.js +0 -2
  511. /package/dist/bundle/chunks/{chunk-UQSONZLL.js → chunk-DN7SM3LX.js} +0 -0
  512. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-MOOADNVS.js} +0 -0
@@ -1,166 +0,0 @@
1
- import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{source_default}from"./chunk-2MJ6J5N2.js";import{sanitizeBinaryOutput}from"./chunk-AACPRSR2.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-6MSE6LZ3.js";import{CODEMODE_SOURCE_GRAMMAR,renderToolOutputType,renderToolSample,toCodemodeIdentifier}from"./chunk-DQ4G4IS4.js";import{SETTINGS_DEFAULTS}from"./chunk-76YNMQ57.js";import{getCustomThemesDir,getDocsPath,getThemesDir,resolvePath,stripBom}from"./chunk-SYRVFGYE.js";import{__export,__toESM}from"./chunk-HZ2UHMBT.js";var build_exports={};__export(build_exports,{AddImmutable:()=>AddImmutable,AddImmutableDeferred:()=>AddImmutableDeferred,AddOptional:()=>AddOptional,AddOptionalDeferred:()=>AddOptionalDeferred,AddReadonly:()=>AddReadonly,AddReadonlyDeferred:()=>AddReadonlyDeferred,Any:()=>Any,Array:()=>_Array_,ArrayOptions:()=>ArrayOptions,BigInt:()=>BigInt2,BigIntPattern:()=>BigIntPattern,Boolean:()=>Boolean2,Broaden:()=>Broaden,Call:()=>Call2,CallConstruct:()=>CallConstruct,CanComposite:()=>CanComposite,Capitalize:()=>Capitalize,CapitalizeAction:()=>CapitalizeAction,CapitalizeDeferred:()=>CapitalizeDeferred,CapitalizeInstantiate:()=>CapitalizeInstantiate,Codec:()=>Codec,CollapseToObject:()=>CollapseToObject,Compare:()=>Compare,CompareResultDisjoint:()=>CompareResultDisjoint,CompareResultEqual:()=>CompareResultEqual,CompareResultLeftInside:()=>CompareResultLeftInside,CompareResultRightInside:()=>CompareResultRightInside,Composite:()=>Composite,Conditional:()=>Conditional,ConditionalAction:()=>ConditionalAction,ConditionalDeferred:()=>ConditionalDeferred,ConditionalInstantiate:()=>ConditionalInstantiate,Constructor:()=>Constructor,ConstructorOptions:()=>ConstructorOptions,ConstructorParameters:()=>ConstructorParameters,ConstructorParametersAction:()=>ConstructorParametersAction,ConstructorParametersDeferred:()=>ConstructorParametersDeferred,ConstructorParametersInstantiate:()=>ConstructorParametersInstantiate,ConvertToIntegerKey:()=>ConvertToIntegerKey,Cyclic:()=>Cyclic,CyclicCandidates:()=>CyclicCandidates,CyclicCheck:()=>CyclicCheck,CyclicDependencies:()=>CyclicDependencies,CyclicExtends:()=>CyclicExtends,CyclicOptions:()=>CyclicOptions,CyclicTarget:()=>CyclicTarget,Decode:()=>Decode,DecodeBuilder:()=>DecodeBuilder,Deferred:()=>Deferred,Dependent:()=>Dependent,DependentOptions:()=>DependentOptions,Distribute:()=>Distribute,Encode:()=>Encode,EncodeBuilder:()=>EncodeBuilder,Enum:()=>Enum,Evaluate:()=>Evaluate2,EvaluateAction:()=>EvaluateAction,EvaluateDeferred:()=>EvaluateDeferred,EvaluateDependent:()=>EvaluateDependent,EvaluateEnum:()=>EvaluateEnum,EvaluateInstantiate:()=>EvaluateInstantiate,EvaluateIntersect:()=>EvaluateIntersect,EvaluateTemplateLiteral:()=>EvaluateTemplateLiteral,EvaluateType:()=>EvaluateType,EvaluateUnion:()=>EvaluateUnion,EvaluateUnionFast:()=>EvaluateUnionFast,Exclude:()=>Exclude,ExcludeAction:()=>ExcludeAction,ExcludeDeferred:()=>ExcludeDeferred,ExcludeInstantiate:()=>ExcludeInstantiate,Extends:()=>Extends,ExtendsResult:()=>result_exports,Extract:()=>Extract,ExtractAction:()=>ExtractAction,ExtractDeferred:()=>ExtractDeferred,ExtractInstantiate:()=>ExtractInstantiate,Flatten:()=>Flatten,Function:()=>_Function_,FunctionOptions:()=>FunctionOptions,Generic:()=>Generic,Identifier:()=>Identifier,Immutable:()=>Immutable,Index:()=>Index,IndexAction:()=>IndexAction,IndexDeferred:()=>IndexDeferred,IndexInstantiate:()=>IndexInstantiate,Infer:()=>Infer,InstanceType:()=>InstanceType,InstanceTypeAction:()=>InstanceTypeAction,InstanceTypeDeferred:()=>InstanceTypeDeferred,InstanceTypeInstantiate:()=>InstanceTypeInstantiate,Instantiate:()=>Instantiate,InstantiateCyclic:()=>InstantiateCyclic,Integer:()=>Integer,IntegerKey:()=>IntegerKey,IntegerPattern:()=>IntegerPattern,Interface:()=>Interface,InterfaceAction:()=>InterfaceAction,InterfaceDeferred:()=>InterfaceDeferred,InterfaceInstantiate:()=>InterfaceInstantiate,Intersect:()=>Intersect,IntersectOptions:()=>IntersectOptions,InvalidLiteralValue:()=>InvalidLiteralValue,IsAny:()=>IsAny,IsArray:()=>IsArray3,IsBigInt:()=>IsBigInt3,IsBoolean:()=>IsBoolean4,IsCall:()=>IsCall,IsCodec:()=>IsCodec,IsConstructor:()=>IsConstructor3,IsCyclic:()=>IsCyclic,IsDeferred:()=>IsDeferred,IsDependent:()=>IsDependent,IsEnum:()=>IsEnum,IsEnumValue:()=>IsEnumValue,IsFunction:()=>IsFunction3,IsGeneric:()=>IsGeneric,IsIdentifier:()=>IsIdentifier2,IsImmutable:()=>IsImmutable,IsInfer:()=>IsInfer,IsInteger:()=>IsInteger3,IsInterfaceDeferred:()=>IsInterfaceDeferred,IsIntersect:()=>IsIntersect,IsKind:()=>IsKind,IsLiteral:()=>IsLiteral,IsLiteralBigInt:()=>IsLiteralBigInt,IsLiteralBoolean:()=>IsLiteralBoolean,IsLiteralNumber:()=>IsLiteralNumber,IsLiteralString:()=>IsLiteralString,IsLiteralValue:()=>IsLiteralValue,IsNever:()=>IsNever,IsNull:()=>IsNull3,IsNumber:()=>IsNumber4,IsObject:()=>IsObject3,IsOptional:()=>IsOptional,IsParameter:()=>IsParameter,IsReadonly:()=>IsReadonly,IsRecord:()=>IsRecord,IsRef:()=>IsRef,IsRefine:()=>IsRefine,IsRefinement:()=>IsRefinement,IsRest:()=>IsRest,IsSchema:()=>IsSchema,IsString:()=>IsString4,IsSymbol:()=>IsSymbol3,IsTemplateLiteral:()=>IsTemplateLiteral,IsTemplateLiteralDeferred:()=>IsTemplateLiteralDeferred,IsTemplateLiteralFinite:()=>IsTemplateLiteralFinite,IsTemplateLiteralPattern:()=>IsTemplateLiteralPattern,IsThis:()=>IsThis,IsTuple:()=>IsTuple,IsTypeScriptEnumLike:()=>IsTypeScriptEnumLike,IsUndefined:()=>IsUndefined3,IsUnion:()=>IsUnion,IsUnknown:()=>IsUnknown,IsUnsafe:()=>IsUnsafe,IsVoid:()=>IsVoid,KeyOf:()=>KeyOf2,KeyOfAction:()=>KeyOfAction,KeyOfDeferred:()=>KeyOfDeferred,KeyOfInstantiate:()=>KeyOfInstantiate,KeysToIndexer:()=>KeysToIndexer,Literal:()=>Literal,LiteralTypeName:()=>LiteralTypeName,Lowercase:()=>Lowercase,LowercaseAction:()=>LowercaseAction,LowercaseDeferred:()=>LowercaseDeferred,LowercaseInstantiate:()=>LowercaseInstantiate,Mapped:()=>Mapped,MappedAction:()=>MappedAction,MappedDeferred:()=>MappedDeferred,MappedInstantiate:()=>MappedInstantiate,Module:()=>Module2,ModuleDeferred:()=>ModuleDeferred,ModuleInstantiate:()=>ModuleInstantiate,Narrow:()=>Narrow,Never:()=>Never,NeverPattern:()=>NeverPattern,NonNullable:()=>NonNullable,NonNullableAction:()=>NonNullableAction,NonNullableDeferred:()=>NonNullableDeferred,NonNullableInstantiate:()=>NonNullableInstantiate,Null:()=>Null,Number:()=>Number2,NumberKey:()=>NumberKey,NumberPattern:()=>NumberPattern,Object:()=>_Object_,ObjectOptions:()=>ObjectOptions,Omit:()=>Omit,OmitAction:()=>OmitAction,OmitDeferred:()=>OmitDeferred,OmitInstantiate:()=>OmitInstantiate,Optional:()=>Optional,Parameter:()=>Parameter,Parameters:()=>Parameters,ParametersAction:()=>ParametersAction,ParametersDeferred:()=>ParametersDeferred,ParametersInstantiate:()=>ParametersInstantiate,ParsePatternIntoTypes:()=>ParsePatternIntoTypes,ParseTemplateIntoTypes:()=>ParseTemplateIntoTypes,Partial:()=>Partial,PartialAction:()=>PartialAction,PartialDeferred:()=>PartialDeferred,PartialInstantiate:()=>PartialInstantiate,Pick:()=>Pick,PickAction:()=>PickAction,PickDeferred:()=>PickDeferred,PickInstantiate:()=>PickInstantiate,Priority:()=>Priority,PropertyKeys:()=>PropertyKeys,PropertyValues:()=>PropertyValues,Readonly:()=>Readonly,ReadonlyObject:()=>ReadonlyObject,ReadonlyObjectAction:()=>ReadonlyObjectAction,ReadonlyObjectDeferred:()=>ReadonlyObjectDeferred,ReadonlyObjectInstantiate:()=>ReadonlyObjectInstantiate,ReadonlyType:()=>ReadonlyType,Record:()=>Record,RecordAction:()=>RecordAction,RecordDeferred:()=>RecordDeferred,RecordFromPattern:()=>RecordFromPattern,RecordInstantiate:()=>RecordInstantiate,RecordKey:()=>RecordKey,RecordOptions:()=>RecordOptions,RecordPattern:()=>RecordPattern,RecordPatternToType:()=>RecordPatternToType,RecordValue:()=>RecordValue,Ref:()=>Ref,RefInstantiate:()=>RefInstantiate,Refine:()=>Refine,RefineAdd:()=>RefineAdd,RemoveImmutable:()=>RemoveImmutable,RemoveImmutableDeferred:()=>RemoveImmutableDeferred,RemoveOptional:()=>RemoveOptional,RemoveOptionalDeferred:()=>RemoveOptionalDeferred,RemoveReadonly:()=>RemoveReadonly,RemoveReadonlyDeferred:()=>RemoveReadonlyDeferred,Required:()=>Required,RequiredAction:()=>RequiredAction,RequiredArray:()=>RequiredArray,RequiredDeferred:()=>RequiredDeferred,RequiredInstantiate:()=>RequiredInstantiate,Rest:()=>Rest,ReturnType:()=>ReturnType,ReturnTypeAction:()=>ReturnTypeAction,ReturnTypeDeferred:()=>ReturnTypeDeferred,ReturnTypeInstantiate:()=>ReturnTypeInstantiate,Script:()=>Script2,String:()=>String2,StringKey:()=>StringKey,StringPattern:()=>StringPattern,Symbol:()=>Symbol2,TemplateLiteral:()=>TemplateLiteral2,TemplateLiteralCreate:()=>TemplateLiteralCreate,TemplateLiteralDecode:()=>TemplateLiteralDecode,TemplateLiteralDecodeUnsafe:()=>TemplateLiteralDecodeUnsafe,TemplateLiteralDeferred:()=>TemplateLiteralDeferred,TemplateLiteralEncode:()=>TemplateLiteralEncode,TemplateLiteralFromString:()=>TemplateLiteralFromString,TemplateLiteralFromTypes:()=>TemplateLiteralFromTypes,This:()=>This,Tuple:()=>Tuple,TupleOptions:()=>TupleOptions,Type:()=>typebox_exports,TypeScriptEnumToEnumValues:()=>TypeScriptEnumToEnumValues,Uncapitalize:()=>Uncapitalize,UncapitalizeAction:()=>UncapitalizeAction,UncapitalizeDeferred:()=>UncapitalizeDeferred,UncapitalizeInstantiate:()=>UncapitalizeInstantiate,Undefined:()=>Undefined,Union:()=>Union,UnionOptions:()=>UnionOptions,Unknown:()=>Unknown,Unsafe:()=>Unsafe,Uppercase:()=>Uppercase,UppercaseAction:()=>UppercaseAction,UppercaseDeferred:()=>UppercaseDeferred,UppercaseInstantiate:()=>UppercaseInstantiate,Void:()=>Void,With:()=>With2,WithAction:()=>WithAction,WithDeferred:()=>WithDeferred,WithInstantiate:()=>WithInstantiate,_Array_:()=>_Array_,_Function_:()=>_Function_,_Object_:()=>_Object_,default:()=>build_default});var memory_exports={};__export(memory_exports,{Assign:()=>Assign,Clone:()=>Clone,Create:()=>Create,Discard:()=>Discard,Metrics:()=>Metrics,Update:()=>Update});var Metrics={assign:0,create:0,clone:0,discard:0,update:0};var settings_exports={};__export(settings_exports,{Get:()=>Get,Reset:()=>Reset,Set:()=>Set2});var emit_exports={};__export(emit_exports,{And:()=>And,ArrayLiteral:()=>ArrayLiteral,ArrowFunction:()=>ArrowFunction,Call:()=>Call,ConstDeclaration:()=>ConstDeclaration,Constant:()=>Constant,Counted:()=>Counted2,Entries:()=>Entries2,Every:()=>Every2,HasPropertyKey:()=>HasPropertyKey2,If:()=>If,IsArray:()=>IsArray2,IsBigInt:()=>IsBigInt2,IsBoolean:()=>IsBoolean2,IsConstructor:()=>IsConstructor2,IsDeepEqual:()=>IsDeepEqual2,IsEqual:()=>IsEqual2,IsFunction:()=>IsFunction2,IsGreaterEqualThan:()=>IsGreaterEqualThan2,IsGreaterThan:()=>IsGreaterThan2,IsInteger:()=>IsInteger2,IsLessEqualThan:()=>IsLessEqualThan2,IsLessThan:()=>IsLessThan2,IsMaxLength:()=>IsMaxLength3,IsMinLength:()=>IsMinLength3,IsNull:()=>IsNull2,IsNumber:()=>IsNumber2,IsObject:()=>IsObject2,IsObjectNotArray:()=>IsObjectNotArray2,IsString:()=>IsString2,IsSymbol:()=>IsSymbol2,IsUndefined:()=>IsUndefined2,Keys:()=>Keys2,Member:()=>Member,MultipleOf:()=>MultipleOf,New:()=>New,Not:()=>Not,Or:()=>Or,ReduceAnd:()=>ReduceAnd,ReduceOr:()=>ReduceOr,Return:()=>Return,Some:()=>Some2,SomeAll:()=>SomeAll2,Statements:()=>Statements,Ternary:()=>Ternary});var guard_exports={};__export(guard_exports,{CodePointCount:()=>CodePointCount2,Counted:()=>Counted,Entries:()=>Entries,EntriesRegExp:()=>EntriesRegExp,Every:()=>Every,EveryAll:()=>EveryAll,GraphemeCount:()=>GraphemeCount2,HasPropertyKey:()=>HasPropertyKey,IsArray:()=>IsArray,IsBigInt:()=>IsBigInt,IsBoolean:()=>IsBoolean,IsClassInstance:()=>IsClassInstance,IsConstructor:()=>IsConstructor,IsDeepEqual:()=>IsDeepEqual,IsEqual:()=>IsEqual,IsFunction:()=>IsFunction,IsGreaterEqualThan:()=>IsGreaterEqualThan,IsGreaterThan:()=>IsGreaterThan,IsInteger:()=>IsInteger,IsLessEqualThan:()=>IsLessEqualThan,IsLessThan:()=>IsLessThan,IsMaxLength:()=>IsMaxLength2,IsMinLength:()=>IsMinLength2,IsMultipleOf:()=>IsMultipleOf,IsNull:()=>IsNull,IsNumber:()=>IsNumber,IsObject:()=>IsObject,IsObjectNotArray:()=>IsObjectNotArray,IsString:()=>IsString,IsSymbol:()=>IsSymbol,IsUndefined:()=>IsUndefined,IsUnsafePropertyKey:()=>IsUnsafePropertyKey,IsValueLike:()=>IsValueLike,Keys:()=>Keys,ShiftLeft:()=>ShiftLeft,Some:()=>Some,SomeAll:()=>SomeAll,Symbols:()=>Symbols,Values:()=>Values});function IsBetween(value,min,max){return value>=min&&value<=max}function IsZeroWidthJoiner(value){return value===8205}function IsRegionalIndicator(value){return IsBetween(value,127462,127487)}function IsVariationSelector(value){return IsBetween(value,65024,65039)}function IsCombiningMark(value){return IsBetween(value,768,879)||IsBetween(value,6832,6911)||IsBetween(value,7616,7679)||IsBetween(value,65056,65071)}function CodePointLength(value){return value>65535?2:1}function ConsumeModifiers(value,index){for(;index<value.length;){let point=value.codePointAt(index);if(IsCombiningMark(point)||IsVariationSelector(point))index+=CodePointLength(point);else break}return index}function NextGraphemeClusterIndex(value,clusterStart){let startCP=value.codePointAt(clusterStart),clusterEnd=clusterStart+CodePointLength(startCP);for(clusterEnd=ConsumeModifiers(value,clusterEnd);clusterEnd<value.length-1&&IsZeroWidthJoiner(value.codePointAt(clusterEnd));){let nextCP=value.codePointAt(clusterEnd+1);clusterEnd+=1+CodePointLength(nextCP),clusterEnd=ConsumeModifiers(value,clusterEnd)}return IsRegionalIndicator(startCP)&&clusterEnd<value.length&&IsRegionalIndicator(value.codePointAt(clusterEnd))&&(clusterEnd+=CodePointLength(value.codePointAt(clusterEnd))),clusterEnd}function GraphemeCount(value){let count=0,index=0;for(;index<value.length;)index=NextGraphemeClusterIndex(value,index),count++;return count}function CodePointCount(value){let result=0,index=0,prev=0;for(;index<value.length;){let next=value.charCodeAt(index++)>>10;result+=+((prev<<8|next)!==13879),prev=next}return result}function IsMaxLength(value,maxLength){return value.length<=maxLength||value.length<=maxLength<<1&&CodePointCount(value)<=maxLength}function IsMinLength(value,minLength){return value.length>=minLength<<1||value.length>=minLength&&CodePointCount(value)>=minLength}function IsArray(value){return Array.isArray(value)}function IsBigInt(value){return IsEqual(typeof value,"bigint")}function IsBoolean(value){return IsEqual(typeof value,"boolean")}function IsConstructor(value){if(IsUndefined(value)||!IsFunction(value))return!1;let result=Function.prototype.toString.call(value);return!!(/^class\s/.test(result)||/\[native code\]/.test(result))}function IsFunction(value){return IsEqual(typeof value,"function")}function IsInteger(value){return Number.isInteger(value)}function IsNull(value){return IsEqual(value,null)}function IsNumber(value){return Number.isFinite(value)}function IsObjectNotArray(value){return IsObject(value)&&!IsArray(value)}function IsObject(value){return IsEqual(typeof value,"object")&&!IsNull(value)}function IsString(value){return IsEqual(typeof value,"string")}function IsSymbol(value){return IsEqual(typeof value,"symbol")}function IsUndefined(value){return IsEqual(value,void 0)}function IsEqual(left,right){return left===right}function IsGreaterThan(left,right){return left>right}function IsLessThan(left,right){return left<right}function IsLessEqualThan(left,right){return left<=right}function IsGreaterEqualThan(left,right){return left>=right}function IsMultipleOf(dividend,divisor){if(IsBigInt(dividend)||IsBigInt(divisor))return BigInt(dividend)%BigInt(divisor)===0n;let tolerance=1e-10;if(!IsNumber(dividend)||IsInteger(dividend)&&1/divisor%1===0)return!0;let mod=dividend%divisor;return Math.min(Math.abs(mod),Math.abs(mod-divisor),Math.abs(mod+divisor))<tolerance}function IsClassInstance(value){if(!IsObject(value))return!1;let proto=globalThis.Object.getPrototypeOf(value);return IsNull(proto)?!1:IsEqual(typeof proto.constructor,"function")&&!(IsEqual(proto.constructor,globalThis.Object)||IsEqual(proto.constructor.name,"Object"))}function IsValueLike(value){return IsBigInt(value)||IsBoolean(value)||IsNull(value)||IsNumber(value)||IsString(value)||IsUndefined(value)}function GraphemeCount2(value){return GraphemeCount(value)}function CodePointCount2(value){return CodePointCount(value)}function IsMaxLength2(value,maxLength){return IsMaxLength(value,maxLength)}function IsMinLength2(value,minLength){return IsMinLength(value,minLength)}function Every(value,offset,callback){return value.every((item,index)=>index<offset||callback(item,index))}function EveryAll(value,offset,callback){let result=!0;return value.forEach((item,index)=>{index>=offset&&!callback(item,index)&&(result=!1)}),result}function Some(value,callback){return value.some((value2,index)=>callback(value2,index))}function SomeAll(value,callback){let result=!1;return value.forEach((item,index)=>{callback(item,index)&&(result=!0)}),result}function Counted(value,callback){return value.reduce((result,value2,index)=>callback(value2,index)?++result:result,0)}function ShiftLeft(array,true_,false_){return IsEqual(array.length,0)?false_():true_(array[0],array.slice(1))}function IsUnsafePropertyKey(key){return IsEqual(key,"__proto__")||IsEqual(key,"constructor")||IsEqual(key,"prototype")}function HasPropertyKey(value,key){return IsUnsafePropertyKey(key)?Object.prototype.hasOwnProperty.call(value,key):key in value}function EntriesRegExp(value){return Keys(value).map(key=>[new RegExp(`^${key}$`),value[key]])}function Entries(value){return Object.entries(value)}function Keys(value){return Object.getOwnPropertyNames(value)}function Symbols(value){return Object.getOwnPropertySymbols(value)}function Values(value){return Object.values(value)}function DeepEqualObject(left,right){if(!IsObject(right))return!1;let keys=Keys(left);return IsEqual(keys.length,Keys(right).length)&&keys.every(key=>IsDeepEqual(left[key],right[key]))}function DeepEqualArray(left,right){return IsArray(right)&&IsEqual(left.length,right.length)&&left.every((_,index)=>IsDeepEqual(left[index],right[index]))}function IsDeepEqual(left,right){return IsArray(left)?DeepEqualArray(left,right):IsObject(left)?DeepEqualObject(left,right):IsEqual(left,right)}var identifierRegExp=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function IsIdentifier(value){return identifierRegExp.test(value)}function And(left,right){return`(${left} && ${right})`}function Or(left,right){return`(${left} || ${right})`}function Not(expr){return`!(${expr})`}function IsArray2(value){return`Array.isArray(${value})`}function IsBigInt2(value){return`typeof ${value} === "bigint"`}function IsBoolean2(value){return`typeof ${value} === "boolean"`}function IsInteger2(value){return`Number.isInteger(${value})`}function IsNull2(value){return`${value} === null`}function IsNumber2(value){return`Number.isFinite(${value})`}function IsObjectNotArray2(value){return And(IsObject2(value),Not(IsArray2(value)))}function IsObject2(value){return`typeof ${value} === "object" && ${value} !== null`}function IsString2(value){return`typeof ${value} === "string"`}function IsSymbol2(value){return`typeof ${value} === "symbol"`}function IsUndefined2(value){return`${value} === undefined`}function IsFunction2(value){return`typeof ${value} === "function"`}function IsConstructor2(value){return`Guard.IsConstructor(${value})`}function IsEqual2(left,right){return`${left} === ${right}`}function IsGreaterThan2(left,right){return`${left} > ${right}`}function IsLessThan2(left,right){return`${left} < ${right}`}function IsLessEqualThan2(left,right){return`${left} <= ${right}`}function IsGreaterEqualThan2(left,right){return`${left} >= ${right}`}function IsMinLength3(value,length){return`(${value}.length >= ${+length<<1} || (${value}.length >= ${length} && Guard.CodePointCount(${value}) >= ${length}))`}function IsMaxLength3(value,length){return`(${value}.length <= ${length} || (${value}.length <= ${+length<<1} && Guard.CodePointCount(${value}) <= ${length}))`}function Every2(value,offset,params,expression){return IsEqual(offset,"0")?`${value}.every((${params[0]}, ${params[1]}) => (${expression}))`:`${value}.every((${params[0]}, ${params[1]}) => (${params[1]} < ${offset}) || (${expression}))`}function Some2(value,params,expression){return`${value}.some((${params[0]}, ${params[1]}) => ${expression})`}function SomeAll2(value,params,expression){return`((value) => { let result = false; value.forEach((${params[0]}, ${params[1]}) => { if (${expression}) result = true }); return result })(${value})`}function Counted2(value,params,expression){return`${value}.reduce((result, ${params[0]}, ${params[1]}) => (${expression}) ? ++result : result, 0)`}function Entries2(value){return`Object.entries(${value})`}function Keys2(value){return`Object.getOwnPropertyNames(${value})`}function HasPropertyKey2(value,key){return IsEqual(key,'"__proto__"')||IsEqual(key,'"constructor"')?`Object.prototype.hasOwnProperty.call(${value}, ${key})`:`${key} in ${value}`}function IsDeepEqual2(left,right){return`Guard.IsDeepEqual(${left}, ${right})`}function ArrayLiteral(elements){return`[${elements.join(", ")}]`}function ArrowFunction(parameters,body){return`((${parameters.join(", ")}) => ${body})`}function Call(value,arguments_){return`${value}(${arguments_.join(", ")})`}function New(value,arguments_){return`new ${value}(${arguments_.join(", ")})`}function Member(left,right){return`${left}${IsIdentifier(right)?`.${right}`:`[${Constant(right)}]`}`}function Constant(value){if(!IsValueLike(value))throw Error("Unsupported Constant");return IsString(value)?JSON.stringify(value):`${value}`}function Ternary(condition,true_,false_){return`(${condition} ? ${true_} : ${false_})`}function Statements(statements){return`{ ${statements.join("; ")}; }`}function ConstDeclaration(identifier,expression){return`const ${identifier} = ${expression}`}function If(condition,then){return`if(${condition}) { ${then} }`}function Return(expression){return`return ${expression}`}function ReduceAnd(operands){return IsEqual(operands.length,0)?"true":operands.reduce((left,right)=>And(left,right))}function ReduceOr(operands){return IsEqual(operands.length,0)?"false":operands.reduce((left,right)=>Or(left,right))}function MultipleOf(dividend,divisor){return`Guard.IsMultipleOf(${dividend}, ${divisor})`}var globals_exports={};__export(globals_exports,{IsBigInt64Array:()=>IsBigInt64Array,IsBigUint64Array:()=>IsBigUint64Array,IsBoolean:()=>IsBoolean3,IsDate:()=>IsDate,IsFloat32Array:()=>IsFloat32Array,IsFloat64Array:()=>IsFloat64Array,IsInt16Array:()=>IsInt16Array,IsInt32Array:()=>IsInt32Array,IsInt8Array:()=>IsInt8Array,IsMap:()=>IsMap,IsNumber:()=>IsNumber3,IsRegExp:()=>IsRegExp,IsSet:()=>IsSet,IsString:()=>IsString3,IsTypeArray:()=>IsTypeArray,IsUint16Array:()=>IsUint16Array,IsUint32Array:()=>IsUint32Array,IsUint8Array:()=>IsUint8Array,IsUint8ClampedArray:()=>IsUint8ClampedArray});function IsBoolean3(value){return value instanceof Boolean}function IsNumber3(value){return value instanceof Number}function IsString3(value){return value instanceof String}function IsTypeArray(value){return globalThis.ArrayBuffer.isView(value)}function IsInt8Array(value){return value instanceof globalThis.Int8Array}function IsUint8Array(value){return value instanceof globalThis.Uint8Array}function IsUint8ClampedArray(value){return value instanceof globalThis.Uint8ClampedArray}function IsInt16Array(value){return value instanceof globalThis.Int16Array}function IsUint16Array(value){return value instanceof globalThis.Uint16Array}function IsInt32Array(value){return value instanceof globalThis.Int32Array}function IsUint32Array(value){return value instanceof globalThis.Uint32Array}function IsFloat32Array(value){return value instanceof globalThis.Float32Array}function IsFloat64Array(value){return value instanceof globalThis.Float64Array}function IsBigInt64Array(value){return value instanceof globalThis.BigInt64Array}function IsBigUint64Array(value){return value instanceof globalThis.BigUint64Array}function IsRegExp(value){return value instanceof globalThis.RegExp}function IsDate(value){return value instanceof globalThis.Date}function IsSet(value){return value instanceof globalThis.Set}function IsMap(value){return value instanceof globalThis.Map}var guard_default=guard_exports;var settings={immutableTypes:!1,maxErrors:8,maxParseErrors:1,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Reset(){settings.immutableTypes=!1,settings.maxErrors=8,settings.maxParseErrors=1,settings.maxInstantiationCount=128,settings.useAcceleration=!0,settings.exactOptionalPropertyTypes=!1,settings.enumerableKind=!1,settings.correctiveParse=!1,settings.unionPrioritySort=!0}function Set2(options2){for(let key of guard_exports.Keys(options2)){let value=options2[key];value!==void 0&&Object.defineProperty(settings,key,{value})}}function Get(){return settings}function Freeze(value){return settings_exports.Get().immutableTypes?Object.freeze(value):value}function Assign(left,right){return Metrics.assign+=1,Freeze({...left,...right})}function IsSchemaObject(value){return guard_exports.HasPropertyKey(value,"~kind")||guard_exports.HasPropertyKey(value,"~unsafe")}function FromSchemaObject(value){let result={};for(let key of guard_exports.Keys(value)){if(guard_exports.IsUnsafePropertyKey(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);descriptor.value=FromValue(descriptor.value),guard_exports.IsEqual(descriptor.enumerable,!0)?result[key]=descriptor.value:Object.defineProperty(result,key,descriptor)}return result}function FromPlainObject(value){let result={};for(let key of guard_exports.Keys(value))guard_exports.IsUnsafePropertyKey(key)||(result[key]=FromValue(value[key]));for(let key of guard_exports.Symbols(value))result[key]=FromValue(value[key]);return result}function FromObject(value){return guard_exports.IsClassInstance(value)?value:IsSchemaObject(value)?FromSchemaObject(value):FromPlainObject(value)}function FromArray(value){return value.map(element=>FromValue(element))}function FromTypedArray(value){return value.slice()}function FromRegExp(value){return new RegExp(value.source,value.flags)}function FromMap(value){return new Map(FromValue([...value.entries()]))}function FromSet(value){return new Set(FromValue([...value.values()]))}function FromValue(value){return globals_exports.IsTypeArray(value)?FromTypedArray(value):globals_exports.IsRegExp(value)?FromRegExp(value):globals_exports.IsMap(value)?FromMap(value):globals_exports.IsSet(value)?FromSet(value):guard_exports.IsArray(value)?FromArray(value):guard_exports.IsObject(value)?FromObject(value):value}function Clone(value){return Metrics.clone+=1,FromValue(value)}function MergeHidden(left,right){for(let key of Object.keys(right))Object.defineProperty(left,key,{configurable:!0,writable:!0,enumerable:!1,value:right[key]});return left}function Merge(left,right){return{...left,...right}}function Create(hidden,enumerable,options2={}){Metrics.create+=1;let withOptions=Merge(enumerable,options2),withHidden=settings_exports.Get().enumerableKind?Merge(withOptions,hidden):MergeHidden(withOptions,hidden);return Freeze(withHidden)}function Discard(value,propertyKeys){Metrics.discard+=1;let result={};for(let key of guard_exports.Keys(value)){if(propertyKeys.includes(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);descriptor.value=Clone(descriptor.value),Object.defineProperty(result,key,descriptor)}return Freeze(result)}function Update(current,hidden,enumerable){Metrics.update+=1;let settings2=settings_exports.Get(),result=Clone(current);for(let key of Object.keys(hidden))Object.defineProperty(result,key,{configurable:!0,writable:!0,enumerable:settings2.enumerableKind,value:hidden[key]});for(let key of Object.keys(enumerable))Object.defineProperty(result,key,{configurable:!0,enumerable:!0,writable:!0,value:enumerable[key]});return Freeze(result)}function IsKind(value,kind){return guard_exports.IsObject(value)&&guard_exports.HasPropertyKey(value,"~kind")&&guard_exports.IsEqual(value["~kind"],kind)}function IsSchema(value){return guard_exports.IsObject(value)}function Deferred(action,parameters,options2){return memory_exports.Create({"~kind":"Deferred"},{type:"deferred",action,parameters,options:options2},{})}function IsDeferred(value){return IsKind(value,"Deferred")}function AddReadonlyOperation(type){return memory_exports.Update(type,{"~readonly":!0},{})}function AddReadonlyAction(type,options2){return memory_exports.Update(AddReadonlyOperation(type),{},options2)}function AddReadonlyInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return AddReadonlyAction(instantiatedType,options2)}function AddOptionalOperation(type){return memory_exports.Update(type,{"~optional":!0},{})}function AddOptionalAction(type,options2){return memory_exports.Update(AddOptionalOperation(type),{},options2)}function AddOptionalInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return AddOptionalAction(instantiatedType,options2)}function _Array_(items,options2){return memory_exports.Create({"~kind":"Array"},{type:"array",items},options2)}function IsArray3(value){return IsKind(value,"Array")}function ArrayOptions(type){return memory_exports.Discard(type,["~kind","type","items"])}function Constructor(parameters,instanceType,options2={}){return memory_exports.Create({"~kind":"Constructor"},{type:"constructor",parameters,instanceType},options2)}function IsConstructor3(value){return IsKind(value,"Constructor")}function ConstructorOptions(type){return memory_exports.Discard(type,["~kind","type","parameters","instanceType"])}function _Function_(parameters,returnType,options2={}){return memory_exports.Create({"~kind":"Function"},{type:"function",parameters,returnType},options2)}function IsFunction3(value){return IsKind(value,"Function")}function FunctionOptions(type){return memory_exports.Discard(type,["~kind","type","parameters","returnType"])}function Ref(ref,options2){return memory_exports.Create({"~kind":"Ref"},{$ref:ref},options2)}function IsRef(value){return IsKind(value,"Ref")}function Generic(parameters,expression){return memory_exports.Create({"~kind":"Generic"},{type:"generic",parameters,expression})}function IsGeneric(value){return IsKind(value,"Generic")}function Any(options2){return memory_exports.Create({"~kind":"Any"},{},options2)}function IsAny(value){return IsKind(value,"Any")}var NeverPattern="(?!)";function Never(options2){return memory_exports.Create({"~kind":"Never"},{not:{}},options2)}function IsNever(value){return IsKind(value,"Never")}function AddOptionalDeferred(type,options2={}){return Deferred("AddOptional",[type],options2)}function AddOptional(type,options2={}){return AddOptionalAction(type,options2)}function Optional(type){return AddOptional(type)}function IsOptional(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"~optional")}function RequiredArray(properties){return guard_exports.Keys(properties).filter(key=>!IsOptional(properties[key]))}function PropertyKeys(properties){return guard_exports.Keys(properties)}function PropertyValues(properties){return guard_exports.Values(properties)}function _Object_(properties,options2={}){let requiredKeys=RequiredArray(properties),required=requiredKeys.length>0?{required:requiredKeys}:{};return memory_exports.Create({"~kind":"Object"},{type:"object",...required,properties},options2)}function IsObject3(value){return IsKind(value,"Object")}function ObjectOptions(type){return memory_exports.Discard(type,["~kind","type","properties","required"])}function Unknown(options2){return memory_exports.Create({"~kind":"Unknown"},{},options2)}function IsUnknown(value){return IsKind(value,"Unknown")}function Cyclic($defs,$ref,options2){let defs=guard_exports.Keys($defs).reduce((result,key)=>({...result,[key]:memory_exports.Update($defs[key],{},{$id:key})}),{});return memory_exports.Create({"~kind":"Cyclic"},{$defs:defs,$ref},options2)}function IsCyclic(value){return IsKind(value,"Cyclic")}function CyclicOptions(type){return memory_exports.Discard(type,["~kind","$defs","$ref"])}function Unsafe(schema){return memory_exports.Update(schema,{"~unsafe":null},{})}function IsUnsafe(value){return guard_exports.IsObjectNotArray(value)&&guard_exports.HasPropertyKey(value,"~unsafe")&&guard_exports.IsNull(value["~unsafe"])}var arguments_exports={};__export(arguments_exports,{Match:()=>Match});function Match(args,match){return match[args.length]?.(...args)??(()=>{throw Error("Invalid Arguments")})()}function Infer(...args){let[name,extends_]=arguments_exports.Match(args,{2:(name2,extends_2)=>[name2,extends_2,extends_2],1:name2=>[name2,Unknown(),Unknown()]});return memory_exports.Create({"~kind":"Infer"},{type:"infer",name,extends:extends_},{})}function IsInfer(value){return IsKind(value,"Infer")}function Dependent(if_,then_,else_,options2={}){return memory_exports.Create({"~kind":"Dependent"},{if:if_,then:then_,else:else_},options2)}function IsDependent(value){return IsKind(value,"Dependent")}function DependentOptions(type){return memory_exports.Discard(type,["~kind","if","then","else"])}function IsTypeScriptEnumLike(value){return guard_exports.IsObjectNotArray(value)}function TypeScriptEnumToEnumValues(type){return guard_exports.Keys(type).filter(key=>isNaN(key)).reduce((result,key)=>[...result,type[key]],[])}function IsEnumValue(value){return guard_exports.IsString(value)||guard_exports.IsNumber(value)}function Enum(value,options2){let values=IsTypeScriptEnumLike(value)?TypeScriptEnumToEnumValues(value):value;return memory_exports.Create({"~kind":"Enum"},{enum:values},options2)}function IsEnum(value){return IsKind(value,"Enum")}function Intersect(types,options2={}){return memory_exports.Create({"~kind":"Intersect"},{allOf:types},options2)}function IsIntersect(value){return IsKind(value,"Intersect")}function IntersectOptions(type){return memory_exports.Discard(type,["~kind","allOf"])}var environment_exports={};__export(environment_exports,{CanEvaluate:()=>CanEvaluate,Evaluate:()=>Evaluate});var supported;function TryEvaluate(){try{return Evaluate("null")(),!0}catch{return!1}}function CanEvaluate(){return guard_exports.IsUndefined(supported)&&(supported=TryEvaluate()),supported&&settings_exports.Get().useAcceleration}function Evaluate(...args){return new globalThis.Function(...args)}var hash_exports={};__export(hash_exports,{Hash:()=>Hash,HashCode:()=>HashCode});function Unreachable(){throw new Error("Unreachable")}function InstanceKeys(value){let propertyKeys=new Set,current=value;for(;current&&current!==Object.prototype;){for(let key of Reflect.ownKeys(current))key!=="constructor"&&typeof key!="symbol"&&propertyKeys.add(key);current=Object.getPrototypeOf(current)}return[...propertyKeys]}function IsIEEE754(value){return typeof value=="number"}var ByteMarker;(function(ByteMarker2){ByteMarker2[ByteMarker2.Array=0]="Array",ByteMarker2[ByteMarker2.BigInt=1]="BigInt",ByteMarker2[ByteMarker2.Boolean=2]="Boolean",ByteMarker2[ByteMarker2.Date=3]="Date",ByteMarker2[ByteMarker2.Constructor=4]="Constructor",ByteMarker2[ByteMarker2.Function=5]="Function",ByteMarker2[ByteMarker2.Null=6]="Null",ByteMarker2[ByteMarker2.Number=7]="Number",ByteMarker2[ByteMarker2.Object=8]="Object",ByteMarker2[ByteMarker2.RegExp=9]="RegExp",ByteMarker2[ByteMarker2.String=10]="String",ByteMarker2[ByteMarker2.Symbol=11]="Symbol",ByteMarker2[ByteMarker2.TypeArray=12]="TypeArray",ByteMarker2[ByteMarker2.Undefined=13]="Undefined"})(ByteMarker||(ByteMarker={}));var Accumulator=BigInt("14695981039346656037"),[Prime,Size]=[BigInt("1099511628211"),BigInt("18446744073709551616")],Bytes=Array.from({length:256}).map((_,i)=>BigInt(i)),F64=new Float64Array(1),F64In=new DataView(F64.buffer),F64Out=new Uint8Array(F64.buffer);function FNV1A64_OP(byte){Accumulator=Accumulator^Bytes[byte],Accumulator=Accumulator*Prime%Size}function FromArray2(value){FNV1A64_OP(ByteMarker.Array);for(let item of value)FromValue2(item)}function FromBigInt(value){FNV1A64_OP(ByteMarker.BigInt),F64In.setBigInt64(0,value);for(let byte of F64Out)FNV1A64_OP(byte)}function FromBoolean(value){FNV1A64_OP(ByteMarker.Boolean),FNV1A64_OP(value?1:0)}function FromConstructor(value){FNV1A64_OP(ByteMarker.Constructor),FromValue2(value.toString())}function FromDate(value){FNV1A64_OP(ByteMarker.Date),FromValue2(value.getTime())}function FromFunction(value){FNV1A64_OP(ByteMarker.Function),FromValue2(value.toString())}function FromNull(_value){FNV1A64_OP(ByteMarker.Null)}function FromNumber(value){FNV1A64_OP(ByteMarker.Number),F64In.setFloat64(0,value,!0);for(let byte of F64Out)FNV1A64_OP(byte)}function FromObject2(value){FNV1A64_OP(ByteMarker.Object);for(let key of InstanceKeys(value).sort())FromValue2(key),FromValue2(value[key])}function FromRegExp2(value){FNV1A64_OP(ByteMarker.RegExp),FromString(value.toString())}var encoder=new TextEncoder;function FromString(value){FNV1A64_OP(ByteMarker.String);for(let byte of encoder.encode(value))FNV1A64_OP(byte)}function FromSymbol(value){FNV1A64_OP(ByteMarker.Symbol),FromValue2(value.toString())}function FromTypeArray(value){FNV1A64_OP(ByteMarker.TypeArray);let buffer=new Uint8Array(value.buffer);for(let i=0;i<buffer.length;i++)FNV1A64_OP(buffer[i])}function FromUndefined(_value){return FNV1A64_OP(ByteMarker.Undefined)}function FromValue2(value){return globals_exports.IsTypeArray(value)?FromTypeArray(value):globals_exports.IsDate(value)?FromDate(value):globals_exports.IsRegExp(value)?FromRegExp2(value):globals_exports.IsBoolean(value)?FromBoolean(value.valueOf()):globals_exports.IsString(value)?FromString(value.valueOf()):globals_exports.IsNumber(value)?FromNumber(value.valueOf()):IsIEEE754(value)?FromNumber(value):guard_exports.IsArray(value)?FromArray2(value):guard_exports.IsBoolean(value)?FromBoolean(value):guard_exports.IsBigInt(value)?FromBigInt(value):guard_exports.IsConstructor(value)?FromConstructor(value):guard_exports.IsNull(value)?FromNull(value):guard_exports.IsObject(value)?FromObject2(value):guard_exports.IsString(value)?FromString(value):guard_exports.IsSymbol(value)?FromSymbol(value):guard_exports.IsUndefined(value)?FromUndefined(value):guard_exports.IsFunction(value)?FromFunction(value):Unreachable()}function HashCode(value){return Accumulator=BigInt("14695981039346656037"),FromValue2(value),Accumulator}function Hash(value){return HashCode(value).toString(16).padStart(16,"0")}function en_US(error){switch(error.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"dependentRequired":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"exclusiveMinimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"format":return`must match format "${error.params.format}"`;case"if":return`must match "${error.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${error.params.limit} items`;case"maxLength":return`must not have more than ${error.params.limit} characters`;case"maxProperties":return`must not have more than ${error.params.limit} properties`;case"maximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"minItems":return`must not have fewer than ${error.params.limit} items`;case"minLength":return`must not have fewer than ${error.params.limit} characters`;case"minProperties":return`must not have fewer than ${error.params.limit} properties`;case"minimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"multipleOf":return`must be multiple of ${error.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${error.params.pattern}"`;case"propertyNames":return`property names ${error.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${error.params.requiredProperties.join(", ")}`;case"type":return typeof error.params.type=="string"?`must be ${error.params.type}`:`must be either ${error.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return error.params.message;default:return"an unknown validation error occurred"}}var locale=en_US;function Get2(){return locale}var EncodeBuilder=class{constructor(type,decode){this.type=type,this.decode=decode}Encode(callback){let type=this.type,decode=IsCodec(type)?value=>this.decode(type["~codec"].decode(value)):this.decode,encode=IsCodec(type)?value=>type["~codec"].encode(callback(value)):callback,codec={decode,encode};return memory_exports.Update(this.type,{"~codec":codec},{})}},DecodeBuilder=class{constructor(type){this.type=type}Decode(callback){return new EncodeBuilder(this.type,callback)}};function Codec(type){return new DecodeBuilder(type)}function Decode(type,callback){return Codec(type).Decode(callback).Encode(()=>{throw Error("Encode not implemented")})}function Encode(type,callback){return Codec(type).Decode(()=>{throw Error("Decode not implemented")}).Encode(callback)}function IsCodec(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"~codec")&&guard_exports.IsObject(value["~codec"])&&guard_exports.HasPropertyKey(value["~codec"],"encode")&&guard_exports.HasPropertyKey(value["~codec"],"decode")}function Immutable(type){return AddImmutable(type)}function IsImmutable(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"~immutable")}function AddReadonlyDeferred(type,options2={}){return Deferred("AddReadonly",[type],options2)}function AddReadonly(type,options2={}){return AddReadonlyAction(type,options2)}function Readonly(type){return AddReadonly(type)}function IsReadonly(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"~readonly")}function RefineAdd(type,refinement){let refinements=IsRefine(type)?[...type["~refine"],refinement]:[refinement];return memory_exports.Update(type,{"~refine":refinements},{})}function Refine(...args){let[type,check,error]=arguments_exports.Match(args,{3:(type2,check2,error2)=>[type2,check2,error2],2:(type2,check2)=>[type2,check2,()=>"Refine Error"]});return RefineAdd(type,{check,error})}function IsRefinement(value){return guard_exports.IsObjectNotArray(value)&&guard_exports.HasPropertyKey(value,"check")&&guard_exports.HasPropertyKey(value,"error")&&guard_exports.IsFunction(value.check)&&guard_exports.IsFunction(value.error)}function IsRefine(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"~refine")&&guard_exports.IsArray(value["~refine"])&&guard_exports.Every(value["~refine"],0,value2=>IsRefinement(value2))}var BigIntPattern="-?(?:0|[1-9][0-9]*)n";function BigInt2(options2){return memory_exports.Create({"~kind":"BigInt"},{type:"bigint"},options2)}function IsBigInt3(value){return IsKind(value,"BigInt")}function Boolean2(options2){return memory_exports.Create({"~kind":"Boolean"},{type:"boolean"},options2)}function IsBoolean4(value){return IsKind(value,"Boolean")}function Identifier(name){return memory_exports.Create({"~kind":"Identifier"},{name})}function IsIdentifier2(value){return IsKind(value,"Identifier")}var IntegerPattern="-?(?:0|[1-9][0-9]*)";function Integer(options2){return memory_exports.Create({"~kind":"Integer"},{type:"integer"},options2)}function IsInteger3(value){return IsKind(value,"Integer")}var InvalidLiteralValue=class extends Error{constructor(value){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value},writable:!1,configurable:!1,enumerable:!1})}};function LiteralTypeName(value){return guard_exports.IsBigInt(value)?"bigint":guard_exports.IsBoolean(value)?"boolean":guard_exports.IsNumber(value)?"number":guard_exports.IsString(value)?"string":(()=>{throw new InvalidLiteralValue(value)})()}function Literal(value,options2){return memory_exports.Create({"~kind":"Literal"},{type:LiteralTypeName(value),const:value},options2)}function IsLiteralValue(value){return guard_exports.IsBigInt(value)||guard_exports.IsBoolean(value)||guard_exports.IsNumber(value)||guard_exports.IsString(value)}function IsLiteralBigInt(value){return IsLiteral(value)&&guard_exports.IsBigInt(value.const)}function IsLiteralBoolean(value){return IsLiteral(value)&&guard_exports.IsBoolean(value.const)}function IsLiteralNumber(value){return IsLiteral(value)&&guard_exports.IsNumber(value.const)}function IsLiteralString(value){return IsLiteral(value)&&guard_exports.IsString(value.const)}function IsLiteral(value){return IsKind(value,"Literal")}function Null(options2){return memory_exports.Create({"~kind":"Null"},{type:"null"},options2)}function IsNull3(value){return IsKind(value,"Null")}var NumberPattern="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Number2(options2){return memory_exports.Create({"~kind":"Number"},{type:"number"},options2)}function IsNumber4(value){return IsKind(value,"Number")}function Symbol2(options2){return memory_exports.Create({"~kind":"Symbol"},{type:"symbol"},options2)}function IsSymbol3(value){return IsKind(value,"Symbol")}function Parameter(...args){let[name,extends_,equals]=arguments_exports.Match(args,{3:(name2,extends_2,equals2)=>[name2,extends_2,equals2],2:(name2,extends_2)=>[name2,extends_2,extends_2],1:name2=>[name2,Unknown(),Unknown()]});return memory_exports.Create({"~kind":"Parameter"},{name,extends:extends_,equals},{})}function IsParameter(value){return IsKind(value,"Parameter")}var StringPattern=".*";function String2(options2){return memory_exports.Create({"~kind":"String"},{type:"string"},options2)}function IsString4(value){return IsKind(value,"String")}function Union(anyOf,options2={}){return memory_exports.Create({"~kind":"Union"},{anyOf},options2)}function IsUnion(value){return IsKind(value,"Union")}function UnionOptions(type){return memory_exports.Discard(type,["~kind","anyOf"])}function ParsePatternIntoTypes(pattern){let parsed=Pattern(pattern);return guard_exports.IsEqual(parsed.length,2)?parsed[0]:[]}function FromLiteral(_value){return!0}function FromTypesReduce(types){return guard_exports.ShiftLeft(types,(left,right)=>FromType(left)?FromTypesReduce(right):!1,()=>!0)}function FromTypes(types){return guard_exports.IsEqual(types.length,0)?!1:FromTypesReduce(types)}function FromType(type){return IsUnion(type)?FromTypes(type.anyOf):IsLiteral(type)?FromLiteral(type.const):!1}function IsTemplateLiteralFinite(types){return FromTypes(types)}function TemplateLiteralCreate(pattern){return memory_exports.Create({"~kind":"TemplateLiteral"},{type:"string",pattern},{})}function FromLiteralPush(variants,value,result=[]){return guard_exports.ShiftLeft(variants,(left,right)=>FromLiteralPush(right,value,[...result,`${left}${value}`]),()=>result)}function FromLiteral2(variants,value){return guard_exports.IsEqual(variants.length,0)?[`${value}`]:FromLiteralPush(variants,value)}function FromUnion(variants,types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>FromUnion(variants,right,[...result,...FromType2(variants,left)]),()=>result)}function FromType2(variants,type){return IsUnion(type)?FromUnion(variants,type.anyOf):IsLiteral(type)?FromLiteral2(variants,type.const):Unreachable()}function DecodeFromSpan(variants,types){return guard_exports.ShiftLeft(types,(left,right)=>DecodeFromSpan(FromType2(variants,left),right),()=>variants)}function VariantsToLiterals(variants){return variants.map(variant=>Literal(variant))}function DecodeTypesAsUnion(types){let variants=DecodeFromSpan([],types),literals=VariantsToLiterals(variants);return Union(literals)}function DecodeTypes(types){return guard_exports.IsEqual(types.length,0)?Unreachable():guard_exports.IsEqual(types.length,1)&&IsLiteral(types[0])?types[0]:DecodeTypesAsUnion(types)}function TemplateLiteralDecodeUnsafe(pattern){let types=ParsePatternIntoTypes(pattern);return guard_exports.IsEqual(types.length,0)?String2():IsTemplateLiteralFinite(types)?DecodeTypes(types):TemplateLiteralCreate(pattern)}function TemplateLiteralDecode(pattern){let decoded=TemplateLiteralDecodeUnsafe(pattern);return IsTemplateLiteral(decoded)?String2():decoded}function CreateRecord(key,value){let type="object",patternProperties={[key]:value};return memory_exports.Create({"~kind":"Record"},{type,patternProperties})}function FromAnyKey(value){return CreateRecord(StringKey,value)}function FromBooleanKey(value){return _Object_({true:value,false:value})}function Tuple(types,options2={}){let[items,minItems,additionalItems]=[types,types.length,!1];return memory_exports.Create({"~kind":"Tuple"},{type:"array",additionalItems,items,minItems},options2)}function IsTuple(value){return IsKind(value,"Tuple")}function TupleOptions(type){return memory_exports.Discard(type,["~kind","type","items","minItems","additionalItems"])}function RemoveReadonlyOperation(type){return memory_exports.Discard(type,["~readonly"])}function RemoveReadonlyAction(type,options2){return memory_exports.Update(RemoveReadonlyOperation(type),{},options2)}function RemoveReadonlyInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return RemoveReadonlyAction(instantiatedType,options2)}function RemoveReadonlyDeferred(type,options2={}){return Deferred("RemoveReadonly",[type],options2)}function RemoveReadonly(type,options2={}){return RemoveReadonlyAction(type,options2)}function RemoveOptionalOperation(type){return memory_exports.Discard(type,["~optional"])}function RemoveOptionalAction(type,options2){return memory_exports.Update(RemoveOptionalOperation(type),{},options2)}function RemoveOptionalInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return RemoveOptionalAction(instantiatedType,options2)}function RemoveOptionalDeferred(type,options2={}){return Deferred("RemoveOptional",[type],options2)}function RemoveOptional(type,options2={}){return RemoveOptionalAction(type,options2)}function TupleElementsToProperties(types){return types.reduceRight((result2,right,index)=>({[index]:right,...result2}),{})}function TupleToObject(type){let properties=TupleElementsToProperties(type.items);return _Object_(properties)}function CanComposite(type){return IsObject3(type)||IsTuple(type)}function IsReadonlyProperty(left,right){return IsReadonly(left)?!!IsReadonly(right):!1}function IsOptionalProperty(left,right){return IsOptional(left)?!!IsOptional(right):!1}function CompositeProperty(left,right){let isReadonly=IsReadonlyProperty(left,right),isOptional=IsOptionalProperty(left,right),evaluated=EvaluateIntersect([left,right]),property=RemoveReadonly(RemoveOptional(evaluated));return isReadonly&&isOptional?AddReadonly(AddOptional(property)):isReadonly&&!isOptional?AddReadonly(property):!isReadonly&&isOptional?AddOptional(property):property}function CompositePropertyKey(left,right,key){return key in left?key in right?CompositeProperty(left[key],right[key]):left[key]:key in right?right[key]:Never()}function CompositeProperties(left,right){return[...new Set([...guard_exports.Keys(left),...guard_exports.Keys(right)])].reduce((result2,key)=>({...result2,[key]:CompositePropertyKey(left,right,key)}),{})}function GetProperties(type){return IsObject3(type)?type.properties:IsTuple(type)?TupleElementsToProperties(type.items):{}}function Composite(left,right){let leftProperties=GetProperties(left),rightProperties=GetProperties(right),properties=CompositeProperties(leftProperties,rightProperties);return _Object_(properties)}function NarrowCompareRule(left,right){let result=Compare(left,right);return guard_exports.IsEqual(result,CompareResultLeftInside)?left:guard_exports.IsEqual(result,CompareResultRightInside)||guard_exports.IsEqual(result,CompareResultEqual)?right:Never()}function NarrowCompositeRule(left,right){let canCompositeLeft=CanComposite(left),canCompositeRight=CanComposite(right);return canCompositeLeft&&canCompositeRight?Composite(left,right):canCompositeLeft&&!canCompositeRight?left:!canCompositeLeft&&canCompositeRight?right:NarrowCompareRule(left,right)}function Narrow(left,right){return IsNever(left)||IsAny(left)?left:IsUnknown(left)||IsNever(right)||IsAny(right)?right:IsUnknown(right)?left:NarrowCompositeRule(left,right)}function ShouldEvaluate(left,right){return IsUnion(left)||IsUnion(right)}function DistributeOperation(left,right){let evaluatedLeft=EvaluateType(left),evaluatedRight=EvaluateType(right);return ShouldEvaluate(evaluatedLeft,evaluatedRight)?EvaluateIntersect([evaluatedLeft,evaluatedRight]):Narrow(evaluatedLeft,evaluatedRight)}function DistributeType(type,types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>DistributeType(type,right,[...result,DistributeOperation(left,type)]),()=>guard_exports.IsEqual(result.length,0)?[type]:result)}function DistributeUnion(types,distribution,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>DistributeUnion(right,distribution,[...result,...Distribute([left],distribution)]),()=>result)}function Distribute(types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>IsUnion(left)?Distribute(right,DistributeUnion(left.anyOf,result)):Distribute(right,DistributeType(left,result)),()=>result)}function ExcludeType(left,right){let check=Extends({},left,right);return result_exports.IsExtendsTrueLike(check)?[]:[left]}function ExcludeUnion(left,right,result=[]){return guard_exports.ShiftLeft(left,(head,tail)=>ExcludeUnion(tail,right,[...result,...ExcludeType(head,right)]),()=>result)}function ExcludeOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExcludeUnion(canonical,right);return EvaluateUnion(remaining)}function EvaluateDependent(if_,then_,else_){let intersected=EvaluateIntersect([if_,then_]),excluded=ExcludeOperation(else_,if_);return EvaluateUnion([intersected,excluded])}function EvaluateEnum(values,result=[]){return guard_exports.ShiftLeft(values,(left,right)=>EvaluateEnum(right,[...result,Literal(left)]),()=>EvaluateUnion(result))}function EvaluateIntersect(types){let distribution=Distribute(types),broadend=Broaden(distribution);return EvaluateUnion(broadend)}function EvaluateTemplateLiteral(pattern){let evaluated=TemplateLiteralDecode(pattern);return EvaluateType(evaluated)}function EvaluateUnion(types){let broadend=Broaden(types);return EvaluateUnionFast(broadend)}function EvaluateType(type){return IsDependent(type)?EvaluateDependent(type.if,type.then,type.else):IsEnum(type)?EvaluateEnum(type.enum):IsIntersect(type)?EvaluateIntersect(type.allOf):IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsUnion(type)?EvaluateUnion(type.anyOf):type}function EvaluateUnionFast(types){return guard_exports.IsEqual(types.length,1)?types[0]:guard_exports.IsEqual(types.length,0)?Never():Union(types)}function FromEnumKey(values,value){let unionKey=EvaluateEnum(values);return FromKey(unionKey,value)}function FromIntegerKey(_key,value){return CreateRecord(IntegerKey,value)}function FromIntersectKey(types,value){let evaluatedKey=EvaluateIntersect(types);return FromKey(evaluatedKey,value)}function FromLiteralKey(key,value){return guard_exports.IsString(key)||guard_exports.IsNumber(key)?_Object_({[key]:value}):guard_exports.IsEqual(key,!1)?_Object_({false:value}):guard_exports.IsEqual(key,!0)?_Object_({true:value}):_Object_({})}function FromNumberKey(_key,value){return CreateRecord(NumberKey,value)}function FromStringKey(key,value){return guard_exports.HasPropertyKey(key,"pattern")&&(guard_exports.IsString(key.pattern)||key.pattern instanceof RegExp)?CreateRecord(key.pattern.toString(),value):CreateRecord(StringKey,value)}function FromTemplateKey(pattern,value){let types=ParsePatternIntoTypes(pattern);return IsTemplateLiteralFinite(types)?FromKey(EvaluateTemplateLiteral(pattern),value):CreateRecord(pattern,value)}function FlattenType(type){return IsUnion(type)?Flatten(type.anyOf):[type]}function Flatten(types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>Flatten(right,[...result,...FlattenType(left)]),()=>result)}function StringOrNumberCheck(types){return types.some(type=>IsString4(type)||IsNumber4(type)||IsInteger3(type))}function TryBuildRecord(types,value){return guard_exports.IsEqual(StringOrNumberCheck(types),!0)?CreateRecord(StringKey,value):void 0}function CreateProperties(types,value){return types.reduce((result,left)=>IsLiteral(left)&&(guard_exports.IsString(left.const)||guard_exports.IsNumber(left.const))?{...result,[left.const]:value}:result,{})}function CreateObject(types,value){let properties=CreateProperties(types,value);return _Object_(properties)}function FromUnionKey(types,value){let flattened=Flatten(types),record=TryBuildRecord(flattened,value);return IsSchema(record)?record:CreateObject(flattened,value)}function FromKey(key,value){return IsAny(key)?FromAnyKey(value):IsBoolean4(key)?FromBooleanKey(value):IsEnum(key)?FromEnumKey(key.enum,value):IsInteger3(key)?FromIntegerKey(key,value):IsIntersect(key)?FromIntersectKey(key.allOf,value):IsLiteral(key)?FromLiteralKey(key.const,value):IsNumber4(key)?FromNumberKey(key,value):IsUnion(key)?FromUnionKey(key.anyOf,value):IsString4(key)?FromStringKey(key,value):IsTemplateLiteral(key)?FromTemplateKey(key.pattern,value):_Object_({})}function RecordAction(key,value,options2){return CanInstantiate([key])?memory_exports.Update(FromKey(key,value),{},options2):RecordDeferred(key,value,options2)}function RecordInstantiate(context,state,key,value,options2){let instantiatedKey=InstantiateType(context,state,key),instantiatedValue=InstantiateType(context,state,value);return RecordAction(instantiatedKey,instantiatedValue,options2)}var IntegerKey=`^${IntegerPattern}$`,NumberKey=`^${NumberPattern}$`,StringKey=`^${StringPattern}$`;function RecordDeferred(key,value,options2={}){return Deferred("Record",[key,value],options2)}function Record(key,value,options2={}){return RecordAction(key,value,options2)}function RecordFromPattern(pattern,value){return CreateRecord(pattern,value)}function RecordPatternToType(pattern){return guard_exports.IsEqual(pattern,StringKey)?String2():guard_exports.IsEqual(pattern,IntegerKey)?Integer():guard_exports.IsEqual(pattern,NumberKey)?Number2():TemplateLiteralDecodeUnsafe(pattern)}function RecordPattern(type){return guard_exports.Keys(type.patternProperties)[0]}function RecordKey(type){let pattern=RecordPattern(type);return RecordPatternToType(pattern)}function RecordValue(type){return type.patternProperties[RecordPattern(type)]}function IsRecord(value){return IsKind(value,"Record")}function RecordOptions(type){return memory_exports.Discard(type,["~kind","type","patternProperties"])}function Rest(type){return memory_exports.Create({"~kind":"Rest"},{type:"rest",items:type},{})}function IsRest(value){return IsKind(value,"Rest")}function This(options2){return memory_exports.Create({"~kind":"This"},{$ref:"#"},options2)}function IsThis(value){return IsKind(value,"This")}function Undefined(options2){return memory_exports.Create({"~kind":"Undefined"},{type:"undefined"},options2)}function IsUndefined3(value){return IsKind(value,"Undefined")}function Void(options2){return memory_exports.Create({"~kind":"Void"},{type:"void"},options2)}function IsVoid(value){return IsKind(value,"Void")}function IntrinsicOrCall(ref,parameters){return guard_exports.IsEqual(ref,"Array")?_Array_(parameters[0]):guard_exports.IsEqual(ref,"Capitalize")?CapitalizeDeferred(parameters[0]):guard_exports.IsEqual(ref,"ConstructorParameters")?ConstructorParametersDeferred(parameters[0]):guard_exports.IsEqual(ref,"Evaluate")?EvaluateDeferred(parameters[0]):guard_exports.IsEqual(ref,"Exclude")?ExcludeDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"Extract")?ExtractDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"Index")?IndexDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"InstanceType")?InstanceTypeDeferred(parameters[0]):guard_exports.IsEqual(ref,"Lowercase")?LowercaseDeferred(parameters[0]):guard_exports.IsEqual(ref,"NonNullable")?NonNullableDeferred(parameters[0]):guard_exports.IsEqual(ref,"Omit")?OmitDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"Parameters")?ParametersDeferred(parameters[0]):guard_exports.IsEqual(ref,"Partial")?PartialDeferred(parameters[0]):guard_exports.IsEqual(ref,"Pick")?PickDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"Readonly")?ReadonlyObjectDeferred(parameters[0]):guard_exports.IsEqual(ref,"KeyOf")?KeyOfDeferred(parameters[0]):guard_exports.IsEqual(ref,"Record")?RecordDeferred(parameters[0],parameters[1]):guard_exports.IsEqual(ref,"Required")?RequiredDeferred(parameters[0]):guard_exports.IsEqual(ref,"ReturnType")?ReturnTypeDeferred(parameters[0]):guard_exports.IsEqual(ref,"Uncapitalize")?UncapitalizeDeferred(parameters[0]):guard_exports.IsEqual(ref,"Uppercase")?UppercaseDeferred(parameters[0]):CallConstruct(Ref(ref),parameters)}function Unreachable2(){throw Error("Unreachable")}function DelimitedDecode(input,result=[]){return guard_exports.ShiftLeft(input,(left,right)=>DelimitedDecode(right,[...result,left[1]]),()=>result)}function Delimited(input){return guard_exports.IsEqual(input.length,3)?[input[0],...DelimitedDecode(input[1])]:[]}function GenericParameterExtendsEqualsMapping(input){return Parameter(input[0],input[2],input[4])}function GenericParameterExtendsMapping(input){return Parameter(input[0],input[2],input[2])}function GenericParameterEqualsMapping(input){return Parameter(input[0],Unknown(),input[2])}function GenericParameterIdentifierMapping(input){return Parameter(input,Unknown(),Unknown())}function GenericParameterListMapping(input){return Delimited(input)}function GenericParametersMapping(input){return input[1]}function GenericCallArgumentListMapping(input){return Delimited(input)}function GenericCallArgumentsMapping(input){return input[1]}function GenericCallMapping(input){return IntrinsicOrCall(input[0],input[1])}function OptionalSemiColonMapping(input){return null}function KeywordStringMapping(input){return String2()}function KeywordNumberMapping(input){return Number2()}function KeywordBooleanMapping(input){return Boolean2()}function KeywordUndefinedMapping(input){return Undefined()}function KeywordNullMapping(input){return Null()}function KeywordIntegerMapping(input){return Integer()}function KeywordBigIntMapping(input){return BigInt2()}function KeywordUnknownMapping(input){return Unknown()}function KeywordAnyMapping(input){return Any()}function KeywordObjectMapping(input){return _Object_({})}function KeywordNeverMapping(input){return Never()}function KeywordSymbolMapping(input){return Symbol2()}function KeywordVoidMapping(input){return Void()}function KeywordThisMapping(input){return This()}function LiteralBigIntMapping(input){return Literal(BigInt(input))}function LiteralBooleanMapping(input){return Literal(guard_exports.IsEqual(input,"true"))}function LiteralNumberMapping(input){return Literal(parseFloat(input))}function LiteralStringMapping(input){return Literal(input)}function TemplateInterpolateMapping(input){return input[1]}function TemplateSpanMapping(input){return Literal(input)}function TemplateBodyMapping(input){return guard_exports.IsEqual(input.length,3)?[input[0],input[1],...input[2]]:[input[0]]}function TemplateLiteralTypesMapping(input){return input[1]}function TemplateLiteralMapping(input){return TemplateLiteralDeferred(input)}function DependentMapping(input){return guard_exports.IsEqual(input.length,6)?Dependent(input[1],input[3],input[5]):Dependent(input[1],input[3],Unknown())}function KeyOfMapping(input){return input.length>0}function IndexArrayMapping(input){return input.reduce((result,current)=>guard_exports.IsEqual(current.length,3)?[...result,[current[1]]]:[...result,[]],[])}function ExtendsMapping(input){return guard_exports.IsEqual(input.length,6)?[input[1],input[3],input[5]]:[]}function BaseMapping(input){return guard_exports.IsArray(input)&&guard_exports.IsEqual(input.length,3)?input[1]:input}function WithMapping(input){return guard_exports.IsEqual(input.length,2)?input[1]:[]}function FactorIndexArray(Type2,indexArray){return indexArray.reduce((result,left)=>{let _left=left;return guard_exports.IsEqual(_left.length,1)?IndexDeferred(result,_left[0]):guard_exports.IsEqual(_left.length,0)?_Array_(result):Unreachable2()},Type2)}function FactorExtends(type,extend){return guard_exports.IsEqual(extend.length,3)?ConditionalDeferred(type,extend[0],extend[1],extend[2]):type}function FactorWith(type,withClause){return guard_exports.IsArray(withClause)&&guard_exports.IsEqual(withClause.length,0)?type:WithDeferred(type,withClause)}function FactorMapping(input){let[keyOf,type,indexArray,extend,withClause]=input;return FactorWith(FactorExtends(keyOf?KeyOfDeferred(FactorIndexArray(type,indexArray)):FactorIndexArray(type,indexArray),extend),withClause)}function ExprBinaryMapping(left,rest){return guard_exports.IsEqual(rest.length,3)?(()=>{let[operator,right,next]=rest,Schema=ExprBinaryMapping(right,next);if(guard_exports.IsEqual(operator,"&"))return IsIntersect(Schema)?Intersect([left,...Schema.allOf]):Intersect([left,Schema]);if(guard_exports.IsEqual(operator,"|"))return IsUnion(Schema)?Union([left,...Schema.anyOf]):Union([left,Schema]);Unreachable2()})():left}function ExprTermMapping(input){let[left,rest]=input;return ExprBinaryMapping(left,rest)}function ExprMapping(input){let[left,rest]=input;return ExprBinaryMapping(left,rest)}function ExprReadonlyMapping(input){return AddImmutableDeferred(input[1])}function ExprPipeMapping(input){return input[1]}function GenericTypeMapping(input){return Generic(input[0],input[2])}function InferTypeMapping(input){return guard_exports.IsEqual(input.length,4)?Infer(input[1],input[3]):guard_exports.IsEqual(input.length,2)?Infer(input[1],Unknown()):Unreachable2()}function PropertyKeyNumberMapping(input){return`${input}`}function PropertyKeyIndexMapping(input){return IsInteger3(input[3])?IntegerKey:IsNumber4(input[3])?NumberKey:IsSymbol3(input[3])?StringKey:IsString4(input[3])?StringKey:Unreachable2()}function ReadonlyMapping(input){return input.length>0}function OptionalMapping(input){return input.length>0}function PropertyMapping(input){let[isReadonly,key,isOptional,_colon,type]=input;return{[key]:isReadonly&&isOptional?AddReadonlyDeferred(AddOptionalDeferred(type)):isReadonly&&!isOptional?AddReadonlyDeferred(type):!isReadonly&&isOptional?AddOptionalDeferred(type):type}}function PropertyListMapping(input){return Delimited(input)}function PropertiesReduce(propertyList){return propertyList.reduce((result,left)=>guard_exports.HasPropertyKey(left,IntegerKey)||guard_exports.HasPropertyKey(left,NumberKey)||guard_exports.HasPropertyKey(left,StringKey)?[result[0],memory_exports.Assign(result[1],left)]:[memory_exports.Assign(result[0],left),result[1]],[{},{}])}function PropertiesMapping(input){return PropertiesReduce(input[1])}function _Object_Mapping(input){let[properties,patternProperties]=input,options2=guard_exports.IsEqual(guard_exports.Keys(patternProperties).length,0)?{}:{patternProperties};return _Object_(properties,options2)}function ElementNamedMapping(input){return guard_exports.IsEqual(input.length,5)?AddReadonlyDeferred(AddOptionalDeferred(input[4])):guard_exports.IsEqual(input.length,3)?input[2]:guard_exports.IsEqual(input.length,4)?guard_exports.IsEqual(input[2],"readonly")?AddReadonlyDeferred(input[3]):AddOptionalDeferred(input[3]):Unreachable2()}function ElementBaseMapping(input){if(!guard_exports.IsArray(input)||!guard_exports.IsEqual(input.length,3))return input;let[isReadonly,type,isOptional]=input;return isReadonly&&isOptional?AddReadonlyDeferred(AddOptionalDeferred(type)):isReadonly&&!isOptional?AddReadonlyDeferred(type):!isReadonly&&isOptional?AddOptionalDeferred(type):type}function ElementMapping(input){return guard_exports.IsEqual(input.length,2)?Rest(input[1]):guard_exports.IsEqual(input.length,1)?input[0]:Unreachable2()}function ElementListMapping(input){return Delimited(input)}function _Tuple_Mapping(input){return Tuple(input[1])}function ParameterReadonlyOptionalMapping(input){return AddReadonlyDeferred(AddOptionalDeferred(input[4]))}function ParameterReadonlyMapping(input){return AddReadonlyDeferred(input[3])}function ParameterOptionalMapping(input){return AddOptionalDeferred(input[3])}function ParameterTypeMapping(input){return input[2]}function ParameterMapping(input){return guard_exports.IsEqual(input.length,2)?Rest(input[1]):guard_exports.IsEqual(input.length,1)?input[0]:Unreachable2()}function ParameterListMapping(input){return Delimited(input)}function _Function_Mapping(input){return _Function_(input[1],input[4])}function _Constructor_Mapping(input){return Constructor(input[2],input[5])}function ApplyReadonly(state,type){return guard_exports.IsEqual(state,"remove")?RemoveReadonlyDeferred(type):guard_exports.IsEqual(state,"add")?AddReadonlyDeferred(type):type}function MappedReadonlyMapping(input){return guard_exports.IsEqual(input.length,2)&&guard_exports.IsEqual(input[0],"-")?"remove":guard_exports.IsEqual(input.length,2)&&guard_exports.IsEqual(input[0],"+")||guard_exports.IsEqual(input.length,1)?"add":"none"}function ApplyOptional(state,type){return guard_exports.IsEqual(state,"remove")?RemoveOptionalDeferred(type):guard_exports.IsEqual(state,"add")?AddOptionalDeferred(type):type}function MappedOptionalMapping(input){return guard_exports.IsEqual(input.length,2)&&guard_exports.IsEqual(input[0],"-")?"remove":guard_exports.IsEqual(input.length,2)&&guard_exports.IsEqual(input[0],"+")||guard_exports.IsEqual(input.length,1)?"add":"none"}function MappedAsMapping(input){return guard_exports.IsEqual(input.length,2)?[input[1]]:[]}function _Mapped_Mapping(input){return guard_exports.IsArray(input[6])&&guard_exports.IsEqual(input[6].length,1)?MappedDeferred(Identifier(input[3]),input[5],input[6][0],ApplyReadonly(input[1],ApplyOptional(input[8],input[10]))):MappedDeferred(Identifier(input[3]),input[5],Ref(input[3]),ApplyReadonly(input[1],ApplyOptional(input[8],input[10])))}function ReferenceMapping(input){return Ref(input)}function WithBigIntMapping(input){return BigInt(input)}function WithNumberMapping(input){return parseFloat(input)}function WithBooleanMapping(input){return guard_exports.IsEqual(input,"true")}function WithNullMapping(input){return null}function WithPropertyMapping(input){return{[input[0]]:input[2]}}function WithPropertyListMapping(input){return Delimited(input)}function WithObjectMappingReduce(propertyList){return propertyList.reduce((result,left)=>memory_exports.Assign(result,left),{})}function WithObjectMapping(input){return WithObjectMappingReduce(input[1])}function WithElementListMapping(input){return Delimited(input)}function WithArrayMapping(input){return input[1]}function PatternBigIntMapping(input){return BigInt2()}function PatternStringMapping(input){return String2()}function PatternNumberMapping(input){return Number2()}function PatternIntegerMapping(input){return Integer()}function PatternNeverMapping(input){return Never()}function PatternTextMapping(input){return Literal(input)}function PatternGroupMapping(input){return Union(input[1])}function PatternUnionMapping(input){return input.length===3?[...input[0],...input[2]]:input.length===1?[...input[0]]:[]}function PatternTermMapping(input){return[input[0],...input[1]]}function PatternMapping(input){return input[1]}function InterfaceDeclarationHeritageListMapping(input){return Delimited(input)}function InterfaceDeclarationHeritageMapping(input){return guard_exports.IsEqual(input.length,2)?input[1]:[]}function InterfaceDeclarationGenericMapping(input){let parameters=input[2],heritage=input[3],[properties,patternProperties]=input[4],options2=guard_exports.IsEqual(guard_exports.Keys(patternProperties).length,0)?{}:{patternProperties};return{[input[1]]:Generic(parameters,InterfaceDeferred(heritage,properties,options2))}}function InterfaceDeclarationMapping(input){let heritage=input[2],[properties,patternProperties]=input[3],options2=guard_exports.IsEqual(guard_exports.Keys(patternProperties).length,0)?{}:{patternProperties};return{[input[1]]:InterfaceDeferred(heritage,properties,options2)}}function TypeAliasDeclarationGenericMapping(input){return{[input[1]]:Generic(input[2],input[4])}}function TypeAliasDeclarationMapping(input){return{[input[1]]:input[3]}}function ExportKeywordMapping(input){return null}function ModuleDeclarationListMapping(input){return Delimited(input)}function ModuleDeclarationMapping(input){return input[1]}function ModuleMapping(input){let[moduleDeclaration,moduleDeclarationList]=[input[0],input[1]];return ModuleDeferred(memory_exports.Assign(moduleDeclaration,PropertiesReduce(moduleDeclarationList)[0]))}function IsMatch(value){return IsEqual(value.length,2)}function Match2(input,ok,fail){return IsMatch(input)?ok(input[0],input[1]):fail()}function TakeVariant(variant,input){return IsEqual(input.indexOf(variant),0)?[variant,input.slice(variant.length)]:[]}function Take(variants,input){for(let i=0;i<variants.length;i++){let result=TakeVariant(variants[i],input);if(IsMatch(result))return result}return[]}function Range(start,end){return Array.from({length:end-start+1},(_,i)=>String.fromCharCode(start+i))}var Alpha=[...Range(97,122),...Range(65,90)],Zero="0",NonZero=Range(49,57),Digit=[Zero,...NonZero],WhiteSpace=" ",NewLine=`
3
- `;var UnderScore="_",Dot=".",DollarSign="$",Hyphen="-";var LineComment="//",OpenComment="/*",CloseComment="*/";function DiscardMultilineComment(input){let index=input.indexOf(CloseComment);return IsEqual(index,-1)?"":input.slice(index+2)}function DiscardLineComment(input){let index=input.indexOf(NewLine);return IsEqual(index,-1)?"":input.slice(index)}function TrimStartUntilNewline(input){return input.replace(/^[ \t\r\f\v]+/,"")}function TrimWhitespace(input){let trimmed=TrimStartUntilNewline(input);return trimmed.startsWith(OpenComment)?TrimWhitespace(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?TrimWhitespace(DiscardLineComment(trimmed.slice(2))):trimmed}function Trim(input){let trimmed=input.trimStart();return trimmed.startsWith(OpenComment)?Trim(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?Trim(DiscardLineComment(trimmed.slice(2))):trimmed}function Optional2(value,input){return Match2(Take([value],input),(Optional4,Rest2)=>[Optional4,Rest2],()=>["",input])}function IsDiscard(discard,input){return discard.includes(input)}function Many(allowed,discard,input,result=""){return Match2(Take(allowed,input),(Char,Rest2)=>IsDiscard(discard,Char)?Many(allowed,discard,Rest2,result):Many(allowed,discard,Rest2,`${result}${Char}`),()=>[result,input])}function TakeNonZero(input){return Take(NonZero,input)}var AllowedDigits=[...Digit,UnderScore];function TakeDigits(input){return Many(AllowedDigits,[UnderScore],input)}function TakeUnsignedInteger(input){return Match2(Take([Zero],input),(Zero2,ZeroRest)=>[Zero2,ZeroRest],()=>Match2(TakeNonZero(input),(NonZero2,NonZeroRest)=>Match2(TakeDigits(NonZeroRest),(Digits,DigitsRest)=>[`${NonZero2}${Digits}`,DigitsRest],()=>[]),()=>[]))}function UnsignedInteger(input){return TakeUnsignedInteger(Trim(input))}function TakeSign(input){return Optional2(Hyphen,input)}function TakeSignedInteger(input){return Match2(TakeSign(input),(Sign,SignRest)=>Match2(UnsignedInteger(SignRest),(UnsignedInteger2,UnsignedIntegerRest)=>[`${Sign}${UnsignedInteger2}`,UnsignedIntegerRest],()=>[]),()=>[])}function Integer2(input){return TakeSignedInteger(Trim(input))}function TakeBigInt(input){return Match2(Integer2(input),(Integer3,IntegerRest)=>Match2(Take(["n"],IntegerRest),(_N,NRest)=>[`${Integer3}`,NRest],()=>[]),()=>[])}function BigInt3(input){return TakeBigInt(input)}function TakeConst(const_,input){return Take([const_],input)}function Const(const_,input){return IsEqual(const_,"")?["",input]:const_.startsWith(NewLine)?TakeConst(const_,TrimWhitespace(input)):const_.startsWith(WhiteSpace)?TakeConst(const_,input):TakeConst(const_,Trim(input))}var Initial=[...Alpha,UnderScore,DollarSign];function TakeInitial(input){return Take(Initial,input)}var Remaining=[...Initial,...Digit];function TakeRemaining(input,result=""){return Match2(Take(Remaining,input),(Remaining2,RemainingRest)=>TakeRemaining(RemainingRest,`${result}${Remaining2}`),()=>[result,input])}function TakeIdent(input){return Match2(TakeInitial(input),(Initial2,InitialRest)=>Match2(TakeRemaining(InitialRest),(Remaining2,RemainingRest)=>[`${Initial2}${Remaining2}`,RemainingRest],()=>[]),()=>[])}function Ident(input){return TakeIdent(Trim(input))}var AllowedDigits2=[...Digit,UnderScore];function IsLeadingDot(input){return IsMatch(Take([Dot],input))}function TakeFractional(input){return Match2(Many(AllowedDigits2,[UnderScore],input),(Digits,DigitsRest)=>IsEqual(Digits,"")?[]:[Digits,DigitsRest],()=>[])}function LeadingDot(input){return Match2(Take([Dot],input),(Dot2,DotRest)=>Match2(TakeFractional(DotRest),(Fractional,FractionalRest)=>[`0${Dot2}${Fractional}`,FractionalRest],()=>[]),()=>[])}function LeadingInteger(input){return Match2(UnsignedInteger(input),(Integer3,IntegerRest)=>Match2(Take([Dot],IntegerRest),(Dot2,DotRest)=>Match2(TakeFractional(DotRest),(Fractional,FractionalRest)=>[`${Integer3}${Dot2}${Fractional}`,FractionalRest],()=>[`${Integer3}`,DotRest]),()=>[`${Integer3}`,IntegerRest]),()=>[])}function TakeUnsignedNumber(input){return IsLeadingDot(input)?LeadingDot(input):LeadingInteger(input)}function UnsignedNumber(input){return TakeUnsignedNumber(Trim(input))}function TakeSign2(input){return Optional2(Hyphen,input)}function TakeSignedNumber(input){return Match2(TakeSign2(input),(Sign,SignRest)=>Match2(UnsignedNumber(SignRest),(UnsignedInteger2,UnsignedIntegerRest)=>[`${Sign}${UnsignedInteger2}`,UnsignedIntegerRest],()=>[]),()=>[])}function Number3(input){return TakeSignedNumber(Trim(input))}function TakeOne(input){return IsEqual(input,"")?[]:[input.slice(0,1),input.slice(1)]}function IsInputMatchSentinal(end,input){return ShiftLeft(end,(left,right)=>input.startsWith(left)?!0:IsInputMatchSentinal(right,input),()=>!1)}function Until(end,input,result=""){return Match2(TakeOne(input),(One,Rest2)=>IsInputMatchSentinal(end,input)?[result,input]:Until(end,Rest2,`${result}${One}`),()=>[])}function MultiLine(start,end,input){return Match2(Take([start],input),(_,Rest2)=>Match2(Until([end],Rest2),(Until2,UntilRest)=>Match2(Take([end],UntilRest),(_2,Rest3)=>[`${Until2}`,Rest3],()=>[]),()=>[]),()=>[])}function SingleLine(start,end,input){return Match2(Take([start],input),(_,Rest2)=>Match2(Until([NewLine,end],Rest2),(Until2,UntilRest)=>Match2(Take([end],UntilRest),(_2,EndRest)=>[`${Until2}`,EndRest],()=>[]),()=>[]),()=>[])}function Span(start,end,multiLine,input){return multiLine?MultiLine(start,end,Trim(input)):SingleLine(start,end,Trim(input))}function TakeInitial2(quotes,input){return Take(quotes,input)}function TakeSpan(quote,input){return Span(quote,quote,!1,input)}function TakeString(quotes,input){return Match2(TakeInitial2(quotes,input),(Initial2,InitialRest)=>TakeSpan(Initial2,`${Initial2}${InitialRest}`),()=>[])}function String3(quotes,input){return TakeString(quotes,Trim(input))}function Until_1(end,input){return Match2(Until(end,input),(Until2,UntilRest)=>IsEqual(Until2,"")?[]:[Until2,UntilRest],()=>[])}var If2=(result,left,right=()=>[])=>result.length===2?left(result):right(),GenericParameterExtendsEquals=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const("extends",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>If2(Const("=",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[GenericParameterExtendsEqualsMapping(_0),input2]),GenericParameterExtends=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const("extends",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[GenericParameterExtendsMapping(_0),input2]),GenericParameterEquals=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const("=",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[GenericParameterEqualsMapping(_0),input2]),GenericParameterIdentifier=input=>If2(Ident(input),([_0,input2])=>[GenericParameterIdentifierMapping(_0),input2]),GenericParameter=input=>If2(If2(GenericParameterExtendsEquals(input),([_0,input2])=>[_0,input2],()=>If2(GenericParameterExtends(input),([_0,input2])=>[_0,input2],()=>If2(GenericParameterEquals(input),([_0,input2])=>[_0,input2],()=>If2(GenericParameterIdentifier(input),([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[_0,input2]),GenericParameterList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(GenericParameter(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>GenericParameterList_0(input2,[...result,_0]),()=>[result,input]),GenericParameterList=input=>If2(If2(If2(GenericParameter(input),([_0,input2])=>If2(GenericParameterList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[GenericParameterListMapping(_0),input2]),GenericParameters=input=>If2(If2(Const("<",input),([_0,input2])=>If2(GenericParameterList(input2),([_1,input3])=>If2(Const(">",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[GenericParametersMapping(_0),input2]),GenericCallArgumentList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>GenericCallArgumentList_0(input2,[...result,_0]),()=>[result,input]),GenericCallArgumentList=input=>If2(If2(If2(Type(input),([_0,input2])=>If2(GenericCallArgumentList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[GenericCallArgumentListMapping(_0),input2]),GenericCallArguments=input=>If2(If2(Const("<",input),([_0,input2])=>If2(GenericCallArgumentList(input2),([_1,input3])=>If2(Const(">",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[GenericCallArgumentsMapping(_0),input2]),GenericCall=input=>If2(If2(Ident(input),([_0,input2])=>If2(GenericCallArguments(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[GenericCallMapping(_0),input2]),OptionalSemiColon=input=>If2(If2(If2(Const(";",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[OptionalSemiColonMapping(_0),input2]),KeywordString=input=>If2(Const("string",input),([_0,input2])=>[KeywordStringMapping(_0),input2]),KeywordNumber=input=>If2(Const("number",input),([_0,input2])=>[KeywordNumberMapping(_0),input2]),KeywordBoolean=input=>If2(Const("boolean",input),([_0,input2])=>[KeywordBooleanMapping(_0),input2]),KeywordUndefined=input=>If2(Const("undefined",input),([_0,input2])=>[KeywordUndefinedMapping(_0),input2]),KeywordNull=input=>If2(Const("null",input),([_0,input2])=>[KeywordNullMapping(_0),input2]),KeywordInteger=input=>If2(Const("integer",input),([_0,input2])=>[KeywordIntegerMapping(_0),input2]),KeywordBigInt=input=>If2(Const("bigint",input),([_0,input2])=>[KeywordBigIntMapping(_0),input2]),KeywordUnknown=input=>If2(Const("unknown",input),([_0,input2])=>[KeywordUnknownMapping(_0),input2]),KeywordAny=input=>If2(Const("any",input),([_0,input2])=>[KeywordAnyMapping(_0),input2]),KeywordObject=input=>If2(Const("object",input),([_0,input2])=>[KeywordObjectMapping(_0),input2]),KeywordNever=input=>If2(Const("never",input),([_0,input2])=>[KeywordNeverMapping(_0),input2]),KeywordSymbol=input=>If2(Const("symbol",input),([_0,input2])=>[KeywordSymbolMapping(_0),input2]),KeywordVoid=input=>If2(Const("void",input),([_0,input2])=>[KeywordVoidMapping(_0),input2]),KeywordThis=input=>If2(Const("this",input),([_0,input2])=>[KeywordThisMapping(_0),input2]),TemplateInterpolate=input=>If2(If2(Const("${",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const("}",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[TemplateInterpolateMapping(_0),input2]),TemplateSpan=input=>If2(Until(["${","`"],input),([_0,input2])=>[TemplateSpanMapping(_0),input2]),TemplateBody=input=>If2(If2(If2(TemplateSpan(input),([_0,input2])=>If2(TemplateInterpolate(input2),([_1,input3])=>If2(TemplateBody(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2(If2(TemplateSpan(input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2(If2(TemplateSpan(input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>[]))),([_0,input2])=>[TemplateBodyMapping(_0),input2]),TemplateLiteralTypes=input=>If2(If2(Const("`",input),([_0,input2])=>If2(TemplateBody(input2),([_1,input3])=>If2(Const("`",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[TemplateLiteralTypesMapping(_0),input2]),TemplateLiteral=input=>If2(TemplateLiteralTypes(input),([_0,input2])=>[TemplateLiteralMapping(_0),input2]),Dependent2=input=>If2(If2(If2(Const("if",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const("then",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>If2(Const("else",input5),([_4,input6])=>If2(Type(input6),([_5,input7])=>[[_0,_1,_2,_3,_4,_5],input7])))))),([_0,input2])=>[_0,input2],()=>If2(If2(Const("if",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const("then",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[DependentMapping(_0),input2]),LiteralBigInt=input=>If2(BigInt3(input),([_0,input2])=>[LiteralBigIntMapping(_0),input2]),LiteralBoolean=input=>If2(If2(Const("true",input),([_0,input2])=>[_0,input2],()=>If2(Const("false",input),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[LiteralBooleanMapping(_0),input2]),LiteralNumber=input=>If2(Number3(input),([_0,input2])=>[LiteralNumberMapping(_0),input2]),LiteralString=input=>If2(String3(["'",'"'],input),([_0,input2])=>[LiteralStringMapping(_0),input2]),KeyOf=input=>If2(If2(If2(Const("keyof",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[KeyOfMapping(_0),input2]),IndexArray_0=(input,result=[])=>If2(If2(If2(Const("[",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const("]",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2(If2(Const("[",input),([_0,input2])=>If2(Const("]",input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>IndexArray_0(input2,[...result,_0]),()=>[result,input]),IndexArray=input=>If2(IndexArray_0(input),([_0,input2])=>[IndexArrayMapping(_0),input2]),Extends2=input=>If2(If2(If2(Const("extends",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const("?",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>If2(Const(":",input5),([_4,input6])=>If2(Type(input6),([_5,input7])=>[[_0,_1,_2,_3,_4,_5],input7])))))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ExtendsMapping(_0),input2]),Base=input=>If2(If2(If2(Const("(",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Const(")",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2(KeywordString(input),([_0,input2])=>[_0,input2],()=>If2(KeywordNumber(input),([_0,input2])=>[_0,input2],()=>If2(KeywordBoolean(input),([_0,input2])=>[_0,input2],()=>If2(KeywordUndefined(input),([_0,input2])=>[_0,input2],()=>If2(KeywordNull(input),([_0,input2])=>[_0,input2],()=>If2(KeywordInteger(input),([_0,input2])=>[_0,input2],()=>If2(KeywordBigInt(input),([_0,input2])=>[_0,input2],()=>If2(KeywordUnknown(input),([_0,input2])=>[_0,input2],()=>If2(KeywordAny(input),([_0,input2])=>[_0,input2],()=>If2(KeywordObject(input),([_0,input2])=>[_0,input2],()=>If2(KeywordNever(input),([_0,input2])=>[_0,input2],()=>If2(KeywordSymbol(input),([_0,input2])=>[_0,input2],()=>If2(KeywordVoid(input),([_0,input2])=>[_0,input2],()=>If2(KeywordThis(input),([_0,input2])=>[_0,input2],()=>If2(LiteralBigInt(input),([_0,input2])=>[_0,input2],()=>If2(LiteralBoolean(input),([_0,input2])=>[_0,input2],()=>If2(LiteralNumber(input),([_0,input2])=>[_0,input2],()=>If2(LiteralString(input),([_0,input2])=>[_0,input2],()=>If2(TemplateLiteral(input),([_0,input2])=>[_0,input2],()=>If2(Dependent2(input),([_0,input2])=>[_0,input2],()=>If2(_Object_2(input),([_0,input2])=>[_0,input2],()=>If2(_Tuple_(input),([_0,input2])=>[_0,input2],()=>If2(_Constructor_(input),([_0,input2])=>[_0,input2],()=>If2(_Function_2(input),([_0,input2])=>[_0,input2],()=>If2(_Mapped_(input),([_0,input2])=>[_0,input2],()=>If2(GenericCall(input),([_0,input2])=>[_0,input2],()=>If2(Reference(input),([_0,input2])=>[_0,input2],()=>[])))))))))))))))))))))))))))),([_0,input2])=>[BaseMapping(_0),input2]),With=input=>If2(If2(If2(Const("with",input),([_0,input2])=>If2(WithObject(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[WithMapping(_0),input2]),Factor=input=>If2(If2(KeyOf(input),([_0,input2])=>If2(Base(input2),([_1,input3])=>If2(IndexArray(input3),([_2,input4])=>If2(Extends2(input4),([_3,input5])=>If2(With(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[FactorMapping(_0),input2]),ExprTermTail=input=>If2(If2(If2(Const("&",input),([_0,input2])=>If2(Factor(input2),([_1,input3])=>If2(ExprTermTail(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[_0,input2]),ExprTerm=input=>If2(If2(Factor(input),([_0,input2])=>If2(ExprTermTail(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[ExprTermMapping(_0),input2]),ExprTail=input=>If2(If2(If2(Const("|",input),([_0,input2])=>If2(ExprTerm(input2),([_1,input3])=>If2(ExprTail(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[_0,input2]),Expr=input=>If2(If2(ExprTerm(input),([_0,input2])=>If2(ExprTail(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[ExprMapping(_0),input2]),ExprReadonly=input=>If2(If2(Const("readonly",input),([_0,input2])=>If2(Expr(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[ExprReadonlyMapping(_0),input2]),ExprPipe=input=>If2(If2(Const("|",input),([_0,input2])=>If2(Expr(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[ExprPipeMapping(_0),input2]),GenericType=input=>If2(If2(GenericParameters(input),([_0,input2])=>If2(Const("=",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[GenericTypeMapping(_0),input2]),InferType=input=>If2(If2(If2(Const("infer",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(Const("extends",input3),([_2,input4])=>If2(Expr(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[_0,input2],()=>If2(If2(Const("infer",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[InferTypeMapping(_0),input2]),Type=input=>If2(If2(InferType(input),([_0,input2])=>[_0,input2],()=>If2(ExprPipe(input),([_0,input2])=>[_0,input2],()=>If2(ExprReadonly(input),([_0,input2])=>[_0,input2],()=>If2(Expr(input),([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[_0,input2]),PropertyKeyNumber=input=>If2(Number3(input),([_0,input2])=>[PropertyKeyNumberMapping(_0),input2]),PropertyKeyIdent=input=>If2(Ident(input),([_0,input2])=>[_0,input2]),PropertyKeyQuoted=input=>If2(String3(["'",'"'],input),([_0,input2])=>[_0,input2]),PropertyKeyIndex=input=>If2(If2(Const("[",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(Const(":",input3),([_2,input4])=>If2(If2(KeywordInteger(input4),([_02,input5])=>[_02,input5],()=>If2(KeywordNumber(input4),([_02,input5])=>[_02,input5],()=>If2(KeywordString(input4),([_02,input5])=>[_02,input5],()=>If2(KeywordSymbol(input4),([_02,input5])=>[_02,input5],()=>[])))),([_3,input5])=>If2(Const("]",input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[PropertyKeyIndexMapping(_0),input2]),PropertyKey=input=>If2(If2(PropertyKeyNumber(input),([_0,input2])=>[_0,input2],()=>If2(PropertyKeyIdent(input),([_0,input2])=>[_0,input2],()=>If2(PropertyKeyQuoted(input),([_0,input2])=>[_0,input2],()=>If2(PropertyKeyIndex(input),([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[_0,input2]),Readonly2=input=>If2(If2(If2(Const("readonly",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ReadonlyMapping(_0),input2]),Optional3=input=>If2(If2(If2(Const("?",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[OptionalMapping(_0),input2]),Property=input=>If2(If2(Readonly2(input),([_0,input2])=>If2(PropertyKey(input2),([_1,input3])=>If2(Optional3(input3),([_2,input4])=>If2(Const(":",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[PropertyMapping(_0),input2]),PropertyDelimiter=input=>If2(If2(If2(Const(",",input),([_0,input2])=>If2(Const(`
4
- `,input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const(";",input),([_0,input2])=>If2(Const(`
5
- `,input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const(",",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2(If2(Const(";",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2(If2(Const(`
6
- `,input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>[]))))),([_0,input2])=>[_0,input2]),PropertyList_0=(input,result=[])=>If2(If2(PropertyDelimiter(input),([_0,input2])=>If2(Property(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>PropertyList_0(input2,[...result,_0]),()=>[result,input]),PropertyList=input=>If2(If2(If2(Property(input),([_0,input2])=>If2(PropertyList_0(input2),([_1,input3])=>If2(If2(PropertyDelimiter(input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[PropertyListMapping(_0),input2]),Properties=input=>If2(If2(Const("{",input),([_0,input2])=>If2(PropertyList(input2),([_1,input3])=>If2(Const("}",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[PropertiesMapping(_0),input2]),_Object_2=input=>If2(Properties(input),([_0,input2])=>[_Object_Mapping(_0),input2]),ElementNamed=input=>If2(If2(If2(Ident(input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>If2(Const(":",input3),([_2,input4])=>If2(Const("readonly",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[_0,input2],()=>If2(If2(Ident(input),([_0,input2])=>If2(Const(":",input2),([_1,input3])=>If2(Const("readonly",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[_0,input2],()=>If2(If2(Ident(input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>If2(Const(":",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[_0,input2],()=>If2(If2(Ident(input),([_0,input2])=>If2(Const(":",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[ElementNamedMapping(_0),input2]),ElementBase=input=>If2(If2(ElementNamed(input),([_0,input2])=>[_0,input2],()=>If2(If2(Readonly2(input),([_0,input2])=>If2(Type(input2),([_1,input3])=>If2(Optional3(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ElementBaseMapping(_0),input2]),Element=input=>If2(If2(If2(Const("...",input),([_0,input2])=>If2(ElementBase(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(ElementBase(input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ElementMapping(_0),input2]),ElementList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(Element(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>ElementList_0(input2,[...result,_0]),()=>[result,input]),ElementList=input=>If2(If2(If2(Element(input),([_0,input2])=>If2(ElementList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ElementListMapping(_0),input2]),_Tuple_=input=>If2(If2(Const("[",input),([_0,input2])=>If2(ElementList(input2),([_1,input3])=>If2(Const("]",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_Tuple_Mapping(_0),input2]),ParameterReadonlyOptional=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>If2(Const(":",input3),([_2,input4])=>If2(Const("readonly",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[ParameterReadonlyOptionalMapping(_0),input2]),ParameterReadonly=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const(":",input2),([_1,input3])=>If2(Const("readonly",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[ParameterReadonlyMapping(_0),input2]),ParameterOptional=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>If2(Const(":",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[ParameterOptionalMapping(_0),input2]),ParameterType=input=>If2(If2(Ident(input),([_0,input2])=>If2(Const(":",input2),([_1,input3])=>If2(Type(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[ParameterTypeMapping(_0),input2]),ParameterBase=input=>If2(If2(ParameterReadonlyOptional(input),([_0,input2])=>[_0,input2],()=>If2(ParameterReadonly(input),([_0,input2])=>[_0,input2],()=>If2(ParameterOptional(input),([_0,input2])=>[_0,input2],()=>If2(ParameterType(input),([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[_0,input2]),Parameter2=input=>If2(If2(If2(Const("...",input),([_0,input2])=>If2(ParameterBase(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(ParameterBase(input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ParameterMapping(_0),input2]),ParameterList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(Parameter2(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>ParameterList_0(input2,[...result,_0]),()=>[result,input]),ParameterList=input=>If2(If2(If2(Parameter2(input),([_0,input2])=>If2(ParameterList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ParameterListMapping(_0),input2]),_Function_2=input=>If2(If2(Const("(",input),([_0,input2])=>If2(ParameterList(input2),([_1,input3])=>If2(Const(")",input3),([_2,input4])=>If2(Const("=>",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[_Function_Mapping(_0),input2]),_Constructor_=input=>If2(If2(Const("new",input),([_0,input2])=>If2(Const("(",input2),([_1,input3])=>If2(ParameterList(input3),([_2,input4])=>If2(Const(")",input4),([_3,input5])=>If2(Const("=>",input5),([_4,input6])=>If2(Type(input6),([_5,input7])=>[[_0,_1,_2,_3,_4,_5],input7])))))),([_0,input2])=>[_Constructor_Mapping(_0),input2]),MappedReadonly=input=>If2(If2(If2(Const("+",input),([_0,input2])=>If2(Const("readonly",input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const("-",input),([_0,input2])=>If2(Const("readonly",input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const("readonly",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[MappedReadonlyMapping(_0),input2]),MappedOptional=input=>If2(If2(If2(Const("+",input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const("-",input),([_0,input2])=>If2(Const("?",input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const("?",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])))),([_0,input2])=>[MappedOptionalMapping(_0),input2]),MappedAs=input=>If2(If2(If2(Const("as",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[MappedAsMapping(_0),input2]),_Mapped_=input=>If2(If2(Const("{",input),([_0,input2])=>If2(MappedReadonly(input2),([_1,input3])=>If2(Const("[",input3),([_2,input4])=>If2(Ident(input4),([_3,input5])=>If2(Const("in",input5),([_4,input6])=>If2(Type(input6),([_5,input7])=>If2(MappedAs(input7),([_6,input8])=>If2(Const("]",input8),([_7,input9])=>If2(MappedOptional(input9),([_8,input10])=>If2(Const(":",input10),([_9,input11])=>If2(Type(input11),([_10,input12])=>If2(OptionalSemiColon(input12),([_11,input13])=>If2(Const("}",input13),([_12,input14])=>[[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12],input14]))))))))))))),([_0,input2])=>[_Mapped_Mapping(_0),input2]),Reference=input=>If2(Ident(input),([_0,input2])=>[ReferenceMapping(_0),input2]),WithBigInt=input=>If2(BigInt3(input),([_0,input2])=>[WithBigIntMapping(_0),input2]),WithNumber=input=>If2(Number3(input),([_0,input2])=>[WithNumberMapping(_0),input2]),WithBoolean=input=>If2(If2(Const("true",input),([_0,input2])=>[_0,input2],()=>If2(Const("false",input),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[WithBooleanMapping(_0),input2]),WithString=input=>If2(String3(['"',"'"],input),([_0,input2])=>[_0,input2]),WithNull=input=>If2(Const("null",input),([_0,input2])=>[WithNullMapping(_0),input2]),WithUndefined=input=>If2(Const("undefined",input),([_0,input2])=>[void 0,input2]),WithProperty=input=>If2(If2(PropertyKey(input),([_0,input2])=>If2(Const(":",input2),([_1,input3])=>If2(WithValue(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[WithPropertyMapping(_0),input2]),WithPropertyList_0=(input,result=[])=>If2(If2(PropertyDelimiter(input),([_0,input2])=>If2(WithProperty(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>WithPropertyList_0(input2,[...result,_0]),()=>[result,input]),WithPropertyList=input=>If2(If2(If2(WithProperty(input),([_0,input2])=>If2(WithPropertyList_0(input2),([_1,input3])=>If2(If2(PropertyDelimiter(input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[WithPropertyListMapping(_0),input2]),WithObject=input=>If2(If2(Const("{",input),([_0,input2])=>If2(WithPropertyList(input2),([_1,input3])=>If2(Const("}",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[WithObjectMapping(_0),input2]),WithElementList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(WithValue(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>WithElementList_0(input2,[...result,_0]),()=>[result,input]),WithElementList=input=>If2(If2(If2(WithValue(input),([_0,input2])=>If2(WithElementList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[WithElementListMapping(_0),input2]),WithArray=input=>If2(If2(Const("[",input),([_0,input2])=>If2(WithElementList(input2),([_1,input3])=>If2(Const("]",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[WithArrayMapping(_0),input2]),WithValue=input=>If2(If2(WithBigInt(input),([_0,input2])=>[_0,input2],()=>If2(WithNumber(input),([_0,input2])=>[_0,input2],()=>If2(WithBoolean(input),([_0,input2])=>[_0,input2],()=>If2(WithString(input),([_0,input2])=>[_0,input2],()=>If2(WithNull(input),([_0,input2])=>[_0,input2],()=>If2(WithUndefined(input),([_0,input2])=>[_0,input2],()=>If2(WithObject(input),([_0,input2])=>[_0,input2],()=>If2(WithArray(input),([_0,input2])=>[_0,input2],()=>[])))))))),([_0,input2])=>[_0,input2]),PatternBigInt=input=>If2(Const("-?(?:0|[1-9][0-9]*)n",input),([_0,input2])=>[PatternBigIntMapping(_0),input2]),PatternString=input=>If2(Const(".*",input),([_0,input2])=>[PatternStringMapping(_0),input2]),PatternNumber=input=>If2(Const("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",input),([_0,input2])=>[PatternNumberMapping(_0),input2]),PatternInteger=input=>If2(Const("-?(?:0|[1-9][0-9]*)",input),([_0,input2])=>[PatternIntegerMapping(_0),input2]),PatternNever=input=>If2(Const("(?!)",input),([_0,input2])=>[PatternNeverMapping(_0),input2]),PatternText=input=>If2(Until_1(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],input),([_0,input2])=>[PatternTextMapping(_0),input2]),PatternBase=input=>If2(If2(PatternBigInt(input),([_0,input2])=>[_0,input2],()=>If2(PatternString(input),([_0,input2])=>[_0,input2],()=>If2(PatternNumber(input),([_0,input2])=>[_0,input2],()=>If2(PatternInteger(input),([_0,input2])=>[_0,input2],()=>If2(PatternNever(input),([_0,input2])=>[_0,input2],()=>If2(PatternGroup(input),([_0,input2])=>[_0,input2],()=>If2(PatternText(input),([_0,input2])=>[_0,input2],()=>[]))))))),([_0,input2])=>[_0,input2]),PatternGroup=input=>If2(If2(Const("(",input),([_0,input2])=>If2(PatternBody(input2),([_1,input3])=>If2(Const(")",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[PatternGroupMapping(_0),input2]),PatternUnion=input=>If2(If2(If2(PatternTerm(input),([_0,input2])=>If2(Const("|",input2),([_1,input3])=>If2(PatternUnion(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2(If2(PatternTerm(input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[]))),([_0,input2])=>[PatternUnionMapping(_0),input2]),PatternTerm=input=>If2(If2(PatternBase(input),([_0,input2])=>If2(PatternBody(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[PatternTermMapping(_0),input2]),PatternBody=input=>If2(If2(PatternUnion(input),([_0,input2])=>[_0,input2],()=>If2(PatternTerm(input),([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[_0,input2]),Pattern=input=>If2(If2(Const("^",input),([_0,input2])=>If2(PatternBody(input2),([_1,input3])=>If2(Const("$",input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[PatternMapping(_0),input2]),InterfaceDeclarationHeritageList_0=(input,result=[])=>If2(If2(Const(",",input),([_0,input2])=>If2(Type(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>InterfaceDeclarationHeritageList_0(input2,[...result,_0]),()=>[result,input]),InterfaceDeclarationHeritageList=input=>If2(If2(If2(Type(input),([_0,input2])=>If2(InterfaceDeclarationHeritageList_0(input2),([_1,input3])=>If2(If2(Const(",",input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[InterfaceDeclarationHeritageListMapping(_0),input2]),InterfaceDeclarationHeritage=input=>If2(If2(If2(Const("extends",input),([_0,input2])=>If2(InterfaceDeclarationHeritageList(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[InterfaceDeclarationHeritageMapping(_0),input2]),InterfaceDeclarationGeneric=input=>If2(If2(Const("interface",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(GenericParameters(input3),([_2,input4])=>If2(InterfaceDeclarationHeritage(input4),([_3,input5])=>If2(Properties(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[InterfaceDeclarationGenericMapping(_0),input2]),InterfaceDeclaration=input=>If2(If2(Const("interface",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(InterfaceDeclarationHeritage(input3),([_2,input4])=>If2(Properties(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[InterfaceDeclarationMapping(_0),input2]),TypeAliasDeclarationGeneric=input=>If2(If2(Const("type",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(GenericParameters(input3),([_2,input4])=>If2(Const("=",input4),([_3,input5])=>If2(Type(input5),([_4,input6])=>[[_0,_1,_2,_3,_4],input6]))))),([_0,input2])=>[TypeAliasDeclarationGenericMapping(_0),input2]),TypeAliasDeclaration=input=>If2(If2(Const("type",input),([_0,input2])=>If2(Ident(input2),([_1,input3])=>If2(Const("=",input3),([_2,input4])=>If2(Type(input4),([_3,input5])=>[[_0,_1,_2,_3],input5])))),([_0,input2])=>[TypeAliasDeclarationMapping(_0),input2]),ExportKeyword=input=>If2(If2(If2(Const("export",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ExportKeywordMapping(_0),input2]),ModuleDeclarationDelimiter=input=>If2(If2(If2(Const(";",input),([_0,input2])=>If2(Const(`
7
- `,input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[_0,input2],()=>If2(If2(Const(";",input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>If2(If2(Const(`
8
- `,input),([_0,input2])=>[[_0],input2]),([_0,input2])=>[_0,input2],()=>[]))),([_0,input2])=>[_0,input2]),ModuleDeclarationList_0=(input,result=[])=>If2(If2(ModuleDeclarationDelimiter(input),([_0,input2])=>If2(ModuleDeclaration(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>ModuleDeclarationList_0(input2,[...result,_0]),()=>[result,input]),ModuleDeclarationList=input=>If2(If2(If2(ModuleDeclaration(input),([_0,input2])=>If2(ModuleDeclarationList_0(input2),([_1,input3])=>If2(If2(ModuleDeclarationDelimiter(input3),([_02,input4])=>[[_02],input4],()=>[[],input3]),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[_0,input2],()=>If2([[],input],([_0,input2])=>[_0,input2],()=>[])),([_0,input2])=>[ModuleDeclarationListMapping(_0),input2]),ModuleDeclaration=input=>If2(If2(ExportKeyword(input),([_0,input2])=>If2(If2(InterfaceDeclarationGeneric(input2),([_02,input3])=>[_02,input3],()=>If2(InterfaceDeclaration(input2),([_02,input3])=>[_02,input3],()=>If2(TypeAliasDeclarationGeneric(input2),([_02,input3])=>[_02,input3],()=>If2(TypeAliasDeclaration(input2),([_02,input3])=>[_02,input3],()=>[])))),([_1,input3])=>If2(OptionalSemiColon(input3),([_2,input4])=>[[_0,_1,_2],input4]))),([_0,input2])=>[ModuleDeclarationMapping(_0),input2]),Module=input=>If2(If2(ModuleDeclaration(input),([_0,input2])=>If2(ModuleDeclarationList(input2),([_1,input3])=>[[_0,_1],input3])),([_0,input2])=>[ModuleMapping(_0),input2]),Script=input=>If2(If2(Module(input),([_0,input2])=>[_0,input2],()=>If2(GenericType(input),([_0,input2])=>[_0,input2],()=>If2(Type(input),([_0,input2])=>[_0,input2],()=>[]))),([_0,input2])=>[_0,input2]);function ParseTemplateIntoTypes(template){let parsed=TemplateLiteralTypes(`\`${template}\``);return guard_exports.IsEqual(parsed.length,2)?parsed[0]:Unreachable()}function JoinString(input){return input.join("|")}function UnwrapTemplateLiteralPattern(pattern){return pattern.slice(1,pattern.length-1)}function EncodeLiteral(value,right,pattern){return EncodeTypes(right,`${pattern}${value}`)}function EncodeBigInt(right,pattern){return EncodeTypes(right,`${pattern}${BigIntPattern}`)}function EncodeInteger(right,pattern){return EncodeTypes(right,`${pattern}${IntegerPattern}`)}function EncodeNumber(right,pattern){return EncodeTypes(right,`${pattern}${NumberPattern}`)}function EncodeBoolean(right,pattern){return EncodeType(Union([Literal("false"),Literal("true")]),right,pattern)}function EncodeString(right,pattern){return EncodeTypes(right,`${pattern}${StringPattern}`)}function EncodeTemplateLiteral(templatePattern,right,pattern){return EncodeTypes(right,`${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`)}function EncodeTemplateLiteralDeferred(types,right,pattern){let templateLiteral=TemplateLiteralAction(types,{});return EncodeType(templateLiteral,right,pattern)}function EncodeEnum(values,right,pattern){let evaluated=EvaluateEnum(values);return EncodeType(evaluated,right,pattern)}function EncodeUnion(types,right,pattern,result=[]){return guard_exports.ShiftLeft(types,(head,tail)=>EncodeUnion(tail,right,pattern,[...result,EncodeType(head,[],"")]),()=>EncodeTypes(right,`${pattern}(${JoinString(result)})`))}function EncodeType(type,right,pattern){return IsEnum(type)?EncodeEnum(type.enum,right,pattern):IsInteger3(type)?EncodeInteger(right,pattern):IsLiteral(type)?EncodeLiteral(type.const,right,pattern):IsBigInt3(type)?EncodeBigInt(right,pattern):IsBoolean4(type)?EncodeBoolean(right,pattern):IsNumber4(type)?EncodeNumber(right,pattern):IsString4(type)?EncodeString(right,pattern):IsTemplateLiteral(type)?EncodeTemplateLiteral(type.pattern,right,pattern):IsTemplateLiteralDeferred(type)?EncodeTemplateLiteralDeferred(type.parameters[0],right,pattern):IsUnion(type)?EncodeUnion(type.anyOf,right,pattern):NeverPattern}function EncodeTypes(types,pattern){return guard_exports.ShiftLeft(types,(left,right)=>EncodeType(left,right,pattern),()=>pattern)}function EncodePattern(types){return`^${EncodeTypes(types,"")}$`}function TemplateLiteralEncode(types){let pattern=EncodePattern(types);return TemplateLiteralCreate(pattern)}function TemplateLiteralAction(types,options2){return CanInstantiate(types)?memory_exports.Update(TemplateLiteralEncode(types),{},options2):TemplateLiteralDeferred(types,options2)}function TemplateLiteralInstantiate(context,state,types,options2){let instantiatedTypes=InstantiateTypes(context,state,types);return TemplateLiteralAction(instantiatedTypes,options2)}function TemplateLiteralDeferred(types,options2={}){return Deferred("TemplateLiteral",[types],options2)}function IsTemplateLiteralDeferred(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"action")&&guard_exports.IsEqual(value.action,"TemplateLiteral")}function TemplateLiteralFromTypes(types){return TemplateLiteralAction(types,{})}function TemplateLiteralFromString(template){let types=ParseTemplateIntoTypes(template);return TemplateLiteralFromTypes(types)}function TemplateLiteral2(input,options2={}){let type=guard_exports.IsString(input)?TemplateLiteralFromString(input):TemplateLiteralFromTypes(input);return memory_exports.Update(type,{},options2)}function IsTemplateLiteral(value){return IsKind(value,"TemplateLiteral")}var result_exports={};__export(result_exports,{ExtendsFalse:()=>ExtendsFalse,ExtendsTrue:()=>ExtendsTrue,ExtendsUnion:()=>ExtendsUnion,IsExtendsFalse:()=>IsExtendsFalse,IsExtendsTrue:()=>IsExtendsTrue,IsExtendsTrueLike:()=>IsExtendsTrueLike,IsExtendsUnion:()=>IsExtendsUnion,Match:()=>Match3});function ExtendsUnion(inferred){return memory_exports.Create({"~kind":"ExtendsUnion"},{inferred})}function IsExtendsUnion(value){return guard_exports.IsObject(value)&&guard_exports.HasPropertyKey(value,"~kind")&&guard_exports.HasPropertyKey(value,"inferred")&&guard_exports.IsEqual(value["~kind"],"ExtendsUnion")&&guard_exports.IsObject(value.inferred)}function ExtendsTrue(inferred){return memory_exports.Create({"~kind":"ExtendsTrue"},{inferred})}function IsExtendsTrue(value){return guard_exports.IsObject(value)&&guard_exports.HasPropertyKey(value,"~kind")&&guard_exports.HasPropertyKey(value,"inferred")&&guard_exports.IsEqual(value["~kind"],"ExtendsTrue")&&guard_exports.IsObject(value.inferred)}function ExtendsFalse(){return memory_exports.Create({"~kind":"ExtendsFalse"},{})}function IsExtendsFalse(value){return guard_exports.IsObject(value)&&guard_exports.HasPropertyKey(value,"~kind")&&guard_exports.IsEqual(value["~kind"],"ExtendsFalse")}function IsExtendsTrueLike(value){return IsExtendsUnion(value)||IsExtendsTrue(value)}function Match3(result,true_,false_){return IsExtendsTrueLike(result)?true_(result.inferred):false_()}function ExtendsRightInfer(inferred,name,left,right){return Match3(ExtendsLeft(inferred,left,right),checkInferred=>ExtendsTrue(memory_exports.Assign(memory_exports.Assign(inferred,checkInferred),{[name]:left})),()=>ExtendsFalse())}function ExtendsRightAny(inferred,_left){return ExtendsTrue(inferred)}function ExtendsRightDependent(inferred,left,if_,then_,else_){return Match3(ExtendsLeft(inferred,left,if_),inferred2=>Match3(ExtendsLeft(inferred2,left,then_),inferred3=>ExtendsTrue(inferred3),()=>ExtendsFalse()),()=>Match3(ExtendsLeft(inferred,left,else_),inferred2=>ExtendsTrue(inferred2),()=>ExtendsFalse()))}function ExtendsRightEnum(inferred,left,right){let evaluated=EvaluateEnum(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightIntersect(inferred,left,right){return guard_exports.ShiftLeft(right,(head,tail)=>Match3(ExtendsLeft(inferred,left,head),inferred2=>ExtendsRightIntersect(inferred2,left,tail),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsRightTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightUnion(inferred,left,right){return guard_exports.ShiftLeft(right,(head,tail)=>Match3(ExtendsLeft(inferred,left,head),inferred2=>ExtendsTrue(inferred2),()=>ExtendsRightUnion(inferred,left,tail)),()=>ExtendsFalse())}function ExtendsRight(inferred,left,right){return IsAny(right)?ExtendsRightAny(inferred,left):IsDependent(right)?ExtendsRightDependent(inferred,left,right.if,right.then,right.else):IsEnum(right)?ExtendsRightEnum(inferred,left,right.enum):IsInfer(right)?ExtendsRightInfer(inferred,right.name,left,right.extends):IsIntersect(right)?ExtendsRightIntersect(inferred,left,right.allOf):IsTemplateLiteral(right)?ExtendsRightTemplateLiteral(inferred,left,right.pattern):IsUnion(right)?ExtendsRightUnion(inferred,left,right.anyOf):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsAny(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsUnion(inferred)}function ExtendsImmutable(left,right){let isImmutableLeft=IsImmutable(left),isImmutableRight=IsImmutable(right);return isImmutableLeft&&isImmutableRight||!isImmutableLeft&&isImmutableRight?!0:!(isImmutableLeft&&!isImmutableRight)}function ExtendsArray(inferred,arrayLeft,left,right){return IsArray3(right)?ExtendsImmutable(arrayLeft,right)?ExtendsLeft(inferred,left,right.items):ExtendsFalse():ExtendsRight(inferred,arrayLeft,right)}function ExtendsBigInt(inferred,left,right){return IsBigInt3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsBoolean(inferred,left,right){return IsBoolean4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ParameterCompare(inferred,left,leftRest,right,rightRest){let checkLeft=IsInfer(right)?left:right,checkRight=IsInfer(right)?right:left,isLeftOptional=IsOptional(left),isRightOptional=IsOptional(right);return!isLeftOptional&&isRightOptional?ExtendsFalse():Match3(ExtendsLeft(inferred,checkLeft,checkRight),inferred2=>ExtendsParameters(inferred2,leftRest,rightRest),()=>ExtendsFalse())}function ParameterRight(inferred,left,leftRest,rightRest){return guard_exports.ShiftLeft(rightRest,(head,tail)=>ParameterCompare(inferred,left,leftRest,head,tail),()=>IsOptional(left)?ExtendsTrue(inferred):ExtendsFalse())}function ParametersLeft(inferred,left,rightRest){return guard_exports.ShiftLeft(left,(head,tail)=>ParameterRight(inferred,head,tail,rightRest),()=>ExtendsTrue(inferred))}function ExtendsParameters(inferred,left,right){return ParametersLeft(inferred,left,right)}function ExtendsReturnType(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsLeft(inferred,left,right)}function ExtendsConstructor(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsConstructor3(right)?Match3(ExtendsParameters(inferred,parameters,right.parameters),inferred2=>ExtendsReturnType(inferred2,returnType,right.instanceType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsDependent(inferred,if_,then_,else_,right){return Match3(ExtendsLeft(inferred,if_,right),()=>ExtendsLeft(inferred,then_,right),()=>ExtendsLeft(inferred,else_,right))}function ExtendsEnum(inferred,left,right){let evaluated=EvaluateEnum(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsFunction(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsFunction3(right)?Match3(ExtendsParameters(inferred,parameters,right.parameters),inferred2=>ExtendsReturnType(inferred2,returnType,right.returnType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsInteger(inferred,left,right){return IsInteger3(right)?ExtendsTrue(inferred):IsNumber4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsIntersect(inferred,left,right){let evaluated=EvaluateIntersect(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsLiteralValue(inferred,left,right){return left===right?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsLiteralBigInt(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBigInt3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralBoolean(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBoolean4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralNumber(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsNumber4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralString(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsString4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteral(inferred,left,right){return guard_exports.IsBigInt(left.const)?ExtendsLiteralBigInt(inferred,left.const,right):guard_exports.IsBoolean(left.const)?ExtendsLiteralBoolean(inferred,left.const,right):guard_exports.IsNumber(left.const)?ExtendsLiteralNumber(inferred,left.const,right):guard_exports.IsString(left.const)?ExtendsLiteralString(inferred,left.const,right):Unreachable()}function ExtendsNever(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):ExtendsTrue(inferred)}function ExtendsNull(inferred,left,right){return IsNull3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsNumber(inferred,left,right){return IsNumber4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsPropertyOptional(inferred,left,right){return IsOptional(left)?IsOptional(right)?ExtendsTrue(inferred):ExtendsFalse():ExtendsTrue(inferred)}function ExtendsProperty(inferred,left,right){return IsInfer(right)&&IsNever(right.extends)?ExtendsFalse():Match3(ExtendsLeft(inferred,left,right),inferred2=>ExtendsPropertyOptional(inferred2,left,right),()=>ExtendsFalse())}function ExtractInferredProperties(keys,properties){return keys.reduce((result,key)=>key in properties?IsExtendsTrueLike(properties[key])?{...result,...properties[key].inferred}:Unreachable():Unreachable(),{})}function ExtendsPropertiesComparer(inferred,left,right){let properties={};for(let rightKey of guard_exports.Keys(right))properties[rightKey]=rightKey in left?ExtendsProperty({},left[rightKey],right[rightKey]):IsOptional(right[rightKey])?IsInfer(right[rightKey])?ExtendsTrue(memory_exports.Assign(inferred,{[right[rightKey].name]:right[rightKey].extends})):ExtendsTrue(inferred):ExtendsFalse();let checked=guard_exports.Values(properties).every(result=>IsExtendsTrueLike(result)),extracted=checked?ExtractInferredProperties(guard_exports.Keys(properties),properties):{};return checked?ExtendsTrue(extracted):ExtendsFalse()}function ExtendsProperties(inferred,left,right){let compared=ExtendsPropertiesComparer(inferred,left,right);return IsExtendsTrueLike(compared)?ExtendsTrue(memory_exports.Assign(inferred,compared.inferred)):ExtendsFalse()}function ExtendsObjectToObject(inferred,left,right){return ExtendsProperties(inferred,left,right)}function RecordMergeInferred(left,right){return guard_exports.Keys(right).reduce((result,key)=>({...result,[key]:guard_exports.HasPropertyKey(left,key)?IsUnion(result[key])?Union([...result[key].anyOf,right[key]]):Union([left[key],right[key]]):right[key]}),left)}function ExtendsRecordComparer(properties,keys,type,result){return guard_exports.ShiftLeft(keys,(left,right)=>Match3(ExtendsLeft({},properties[left],type),inferred=>ExtendsRecordComparer(properties,right,type,RecordMergeInferred(result,inferred)),()=>ExtendsFalse()),()=>ExtendsTrue(result))}function ExtendsObjectToRecord(inferred,properties,_pattern,value){let keys=guard_exports.Keys(properties);return ExtendsRecordComparer(properties,keys,value,inferred)}function ExtendsObject(inferred,left,right){return IsRecord(right)?ExtendsObjectToRecord(inferred,left,RecordPattern(right),RecordValue(right)):IsObject3(right)?ExtendsObjectToObject(inferred,left,right.properties):ExtendsRight(inferred,_Object_(left),right)}function FromObject3(inferred,properties){return guard_exports.IsEqual(guard_exports.Keys(properties).length,0)?ExtendsTrue(inferred):ExtendsFalse()}function FromRecord(inferred,_leftKey,leftValue,_rightKey,rightValue){return ExtendsLeft(inferred,leftValue,rightValue)}function ExtendsRecord(inferred,leftPattern,leftValue,right){return IsRecord(right)?FromRecord(inferred,RecordPatternToType(leftPattern),leftValue,RecordPatternToType(RecordPattern(right)),RecordValue(right)):IsObject3(right)?FromObject3(inferred,right.properties):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsString(inferred,left,right){return IsString4(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsSymbol(inferred,left,right){return IsSymbol3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(left);return ExtendsLeft(inferred,evaluated,right)}function Inferrable(name,type){return memory_exports.Create({"~kind":"Inferrable"},{name,type},{})}function IsInferable(value){return guard_exports.IsObject(value)&&guard_exports.HasPropertyKey(value,"~kind")&&guard_exports.HasPropertyKey(value,"name")&&guard_exports.HasPropertyKey(value,"type")&&guard_exports.IsEqual(value["~kind"],"Inferrable")&&guard_exports.IsString(value.name)&&guard_exports.IsObject(value.type)}function TryRestInferable(type){return IsRest(type)?IsInfer(type.items)?IsArray3(type.items.extends)?Inferrable(type.items.name,type.items.extends.items):IsUnknown(type.items.extends)?Inferrable(type.items.name,type.items.extends):void 0:Unreachable():void 0}function TryInferable(type){return IsInfer(type)?Inferrable(type.name,type.extends):void 0}function TryInferResults(rest,right){let result=[];for(let head of rest){if(!IsExtendsTrueLike(ExtendsLeft({},head,right)))return;result.push(head)}return result}function InferTupleResult(inferred,name,left,right){let results=TryInferResults(left,right);return guard_exports.IsArray(results)?ExtendsTrue(memory_exports.Assign(inferred,{[name]:Tuple(results)})):ExtendsFalse()}function InferUnionResult(inferred,name,left,right){let results=TryInferResults(left,right);return guard_exports.IsArray(results)?ExtendsTrue(memory_exports.Assign(inferred,{[name]:Union(results)})):ExtendsFalse()}function Reverse(types){return[...types].reverse()}function ApplyReverse(types,reversed){return reversed?Reverse(types):types}function Reversed(types){let first=types.length>0?types[0]:void 0,inferrable=IsSchema(first)?TryRestInferable(first):void 0;return IsSchema(inferrable)}function ElementsCompare(inferred,reversed,left,leftRest,right,rightRest){return Match3(ExtendsLeft(inferred,left,right),checkInferred=>Elements(checkInferred,reversed,leftRest,rightRest),()=>ExtendsFalse())}function ElementsLeft(inferred,reversed,leftRest,right,rightRest){let inferable=TryRestInferable(right);return IsInferable(inferable)?InferTupleResult(inferred,inferable.name,ApplyReverse(leftRest,reversed),inferable.type):guard_exports.ShiftLeft(leftRest,(head,tail)=>ElementsCompare(inferred,reversed,head,tail,right,rightRest),()=>ExtendsFalse())}function ElementsRight(inferred,reversed,leftRest,rightRest){return guard_exports.ShiftLeft(rightRest,(head,tail)=>ElementsLeft(inferred,reversed,leftRest,head,tail),()=>guard_exports.IsEqual(leftRest.length,0)?ExtendsTrue(inferred):ExtendsFalse())}function Elements(inferred,reversed,leftRest,rightRest){return ElementsRight(inferred,reversed,leftRest,rightRest)}function ExtendsTupleToTuple(inferred,left,right){let instantiatedRight=InstantiateElements(inferred,State([],[]),right),reversed=Reversed(instantiatedRight);return Elements(inferred,reversed,ApplyReverse(left,reversed),ApplyReverse(instantiatedRight,reversed))}function ExtendsTupleToArrayReduce(inferred,left,right){for(let head of left){let result=ExtendsLeft(inferred,head,right);if(!IsExtendsTrueLike(result))return result;inferred=result.inferred}return ExtendsTrue(inferred)}function ExtendsTupleToArray(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):ExtendsTupleToArrayReduce(inferred,left,right)}function ExtendsTuple(inferred,left,right){let instantiatedLeft=InstantiateElements(inferred,State([],[]),left);return IsTuple(right)?ExtendsTupleToTuple(inferred,instantiatedLeft,right.items):IsArray3(right)?ExtendsTupleToArray(inferred,instantiatedLeft,right.items):ExtendsRight(inferred,Tuple(instantiatedLeft),right)}function ExtendsUndefined(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):IsUndefined3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsUnionSome(inferred,type,unionTypes){return guard_exports.ShiftLeft(unionTypes,(head,tail)=>Match3(ExtendsLeft(inferred,type,head),inferred2=>ExtendsTrue(inferred2),()=>ExtendsUnionSome(inferred,type,tail)),()=>ExtendsFalse())}function ExtendsUnionLeft(inferred,left,right){return guard_exports.ShiftLeft(left,(head,tail)=>Match3(ExtendsUnionSome(inferred,head,right),inferred2=>ExtendsUnionLeft(inferred2,tail,right),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsUnion2(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):IsUnion(right)?ExtendsUnionLeft(inferred,left,right.anyOf):ExtendsUnionLeft(inferred,left,[right])}function ExtendsUnknown(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsVoid(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsLeft(inferred,left,right){return IsAny(left)?ExtendsAny(inferred,left,right):IsArray3(left)?ExtendsArray(inferred,left,left.items,right):IsBigInt3(left)?ExtendsBigInt(inferred,left,right):IsBoolean4(left)?ExtendsBoolean(inferred,left,right):IsConstructor3(left)?ExtendsConstructor(inferred,left.parameters,left.instanceType,right):IsDependent(left)?ExtendsDependent(inferred,left.if,left.then,left.else,right):IsEnum(left)?ExtendsEnum(inferred,left.enum,right):IsFunction3(left)?ExtendsFunction(inferred,left.parameters,left.returnType,right):IsInteger3(left)?ExtendsInteger(inferred,left,right):IsIntersect(left)?ExtendsIntersect(inferred,left.allOf,right):IsLiteral(left)?ExtendsLiteral(inferred,left,right):IsNever(left)?ExtendsNever(inferred,left,right):IsNull3(left)?ExtendsNull(inferred,left,right):IsNumber4(left)?ExtendsNumber(inferred,left,right):IsObject3(left)?ExtendsObject(inferred,left.properties,right):IsRecord(left)?ExtendsRecord(inferred,RecordPattern(left),RecordValue(left),right):IsString4(left)?ExtendsString(inferred,left,right):IsSymbol3(left)?ExtendsSymbol(inferred,left,right):IsTemplateLiteral(left)?ExtendsTemplateLiteral(inferred,left.pattern,right):IsTuple(left)?ExtendsTuple(inferred,left.items,right):IsUndefined3(left)?ExtendsUndefined(inferred,left,right):IsUnion(left)?ExtendsUnion2(inferred,left.anyOf,right):IsUnknown(left)?ExtendsUnknown(inferred,left,right):IsVoid(left)?ExtendsVoid(inferred,left,right):ExtendsFalse()}function InterfaceOperation(heritage,properties){return EvaluateIntersect([...heritage,_Object_(properties)])}function InterfaceAction(heritage,properties,options2){return CanInstantiate(heritage)?memory_exports.Update(InterfaceOperation(heritage,properties),{},options2):InterfaceDeferred(heritage,properties,options2)}function InterfaceInstantiate(context,state,heritage,properties,options2){let instantiatedHeritage=InstantiateTypes(context,state,heritage),instantiatedProperties=InstantiateProperties(context,state,properties);return InterfaceAction(instantiatedHeritage,instantiatedProperties,options2)}function InterfaceDeferred(heritage,properties,options2={}){return Deferred("Interface",[heritage,properties],options2)}function IsInterfaceDeferred(value){return IsSchema(value)&&guard_exports.HasPropertyKey(value,"action")&&guard_exports.IsEqual(value.action,"Interface")}function Interface(heritage,properties,options2={}){return InterfaceAction(heritage,properties,options2)}function FromRef(stack,context,ref){return stack.includes(ref)?!0:FromType3([...stack,ref],context,context[ref])}function FromProperties(stack,context,properties){let types=PropertyValues(properties);return FromTypes2(stack,context,types)}function FromTypes2(stack,context,types){return guard_exports.ShiftLeft(types,(left,right)=>FromType3(stack,context,left)?!0:FromTypes2(stack,context,right),()=>!1)}function FromType3(stack,context,type){return IsRef(type)?FromRef(stack,context,type.$ref):IsArray3(type)?FromType3(stack,context,type.items):IsConstructor3(type)?FromTypes2(stack,context,[...type.parameters,type.instanceType]):IsFunction3(type)?FromTypes2(stack,context,[...type.parameters,type.returnType]):IsInterfaceDeferred(type)?FromProperties(stack,context,type.parameters[1]):IsIntersect(type)?FromTypes2(stack,context,type.allOf):IsObject3(type)?FromProperties(stack,context,type.properties):IsUnion(type)?FromTypes2(stack,context,type.anyOf):IsTuple(type)?FromTypes2(stack,context,type.items):IsRecord(type)?FromType3(stack,context,RecordValue(type)):!1}function CyclicCheck(stack,context,type){return FromType3(stack,context,type)}function ResolveCandidateKeys(context,keys){return keys.reduce((result,left)=>CyclicCheck([left],context,context[left])?[...result,left]:result,[])}function CyclicCandidates(context){let keys=PropertyKeys(context);return ResolveCandidateKeys(context,keys)}function FromRef2(context,ref,result){return result.includes(ref)?result:ref in context?FromType4(context,context[ref],[...result,ref]):Unreachable()}function FromProperties2(context,properties,result){let types=PropertyValues(properties);return FromTypes3(context,types,result)}function FromTypes3(context,types,result){return types.reduce((result2,left)=>FromType4(context,left,result2),result)}function FromType4(context,type,result){return IsRef(type)?FromRef2(context,type.$ref,result):IsArray3(type)?FromType4(context,type.items,result):IsConstructor3(type)?FromTypes3(context,[...type.parameters,type.instanceType],result):IsFunction3(type)?FromTypes3(context,[...type.parameters,type.returnType],result):IsInterfaceDeferred(type)?FromProperties2(context,type.parameters[1],result):IsIntersect(type)?FromTypes3(context,type.allOf,result):IsObject3(type)?FromProperties2(context,type.properties,result):IsUnion(type)?FromTypes3(context,type.anyOf,result):IsTuple(type)?FromTypes3(context,type.items,result):IsRecord(type)?FromType4(context,RecordValue(type),result):result}function CyclicDependencies(context,key,type){return FromType4(context,type,[key])}function FromRef3(_ref){return Any()}function FromProperties3(properties){return guard_exports.Keys(properties).reduce((result,key)=>({...result,[key]:FromType5(properties[key])}),{})}function FromTypes4(types){return types.reduce((result,left)=>[...result,FromType5(left)],[])}function FromType5(type){return IsRef(type)?FromRef3(type.$ref):IsArray3(type)?_Array_(FromType5(type.items),ArrayOptions(type)):IsConstructor3(type)?Constructor(FromTypes4(type.parameters),FromType5(type.instanceType)):IsFunction3(type)?_Function_(FromTypes4(type.parameters),FromType5(type.returnType)):IsIntersect(type)?Intersect(FromTypes4(type.allOf)):IsObject3(type)?_Object_(FromProperties3(type.properties)):IsRecord(type)?Record(RecordKey(type),FromType5(RecordValue(type))):IsUnion(type)?Union(FromTypes4(type.anyOf)):IsTuple(type)?Tuple(FromTypes4(type.items)):type}function CyclicAnyFromParameters(defs,ref){return ref in defs?FromType5(defs[ref]):Unknown()}function CyclicExtends(type){return CyclicAnyFromParameters(type.$defs,type.$ref)}function CyclicInterface(context,heritage,properties){let instantiatedHeritage=InstantiateTypes(context,State([],[]),heritage),instantiatedProperties=InstantiateProperties({},State([],[]),properties);return EvaluateIntersect([...instantiatedHeritage,_Object_(instantiatedProperties)])}function CyclicDefinitions(context,dependencies){return guard_exports.Keys(context).filter(key=>dependencies.includes(key)).reduce((result,key)=>{let type=context[key],instantiatedType=IsInterfaceDeferred(type)?CyclicInterface(context,type.parameters[0],type.parameters[1]):type;return{...result,[key]:instantiatedType}},{})}function InstantiateCyclic(context,ref,type){let dependencies=CyclicDependencies(context,ref,type),definitions=CyclicDefinitions(context,dependencies);return Cyclic(definitions,ref)}function Resolve(defs,ref){return ref in defs?IsRef(defs[ref])?Resolve(defs,defs[ref].$ref):defs[ref]:Never()}function CyclicTarget(defs,ref){return Resolve(defs,ref)}function Canonical(type){return IsCyclic(type)?CyclicExtends(type):IsUnsafe(type)?Unknown():type}function Extends(inferred,left,right){let canonicalLeft=Canonical(left),canonicalRight=Canonical(right);return ExtendsLeft(inferred,canonicalLeft,canonicalRight)}var CompareResultEqual=0,CompareResultDisjoint=1,CompareResultLeftInside=2,CompareResultRightInside=3;function Compare(left,right){let extendsCheck=[Extends({},left,right),Extends({},right,left)];return result_exports.IsExtendsTrueLike(extendsCheck[0])&&result_exports.IsExtendsTrueLike(extendsCheck[1])?CompareResultEqual:result_exports.IsExtendsTrueLike(extendsCheck[0])&&result_exports.IsExtendsFalse(extendsCheck[1])?CompareResultLeftInside:result_exports.IsExtendsFalse(extendsCheck[0])&&result_exports.IsExtendsTrueLike(extendsCheck[1])?CompareResultRightInside:CompareResultDisjoint}function BroadenFilter(type,types,result=[],all=types){return guard_exports.ShiftLeft(types,(left,right)=>{let compare=Compare(type,left);return guard_exports.IsEqual(compare,CompareResultLeftInside)||guard_exports.IsEqual(compare,CompareResultEqual)?all:guard_exports.IsEqual(compare,CompareResultDisjoint)?BroadenFilter(type,right,[...result,left],all):BroadenFilter(type,right,result,all)},()=>[...result,type])}function BroadenType(type,types,result){let evaluated=EvaluateType(type);return IsAny(evaluated)?[evaluated]:IsUnknown(evaluated)?[evaluated]:IsNever(evaluated)?BroadenTypes(types,result):IsObject3(evaluated)?BroadenTypes(types,[...result,evaluated]):BroadenTypes(types,BroadenFilter(evaluated,result))}function BroadenTypes(types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>BroadenType(left,right,result),()=>result)}function Broaden(types){let broadened=BroadenTypes(types);return Flatten(broadened)}function EvaluateAction(type,options2){return memory_exports.Update(EvaluateType(type),{},options2)}function EvaluateInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return EvaluateAction(instantiatedType,options2)}function CollectDistributionNames(expression,result=[]){return IsDeferred(expression)&&guard_exports.IsEqual(expression.action,"Conditional")?IsRef(expression.parameters[0])?CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],[...result,expression.parameters[0].$ref])):CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],result)):IsDeferred(expression)&&guard_exports.IsEqual(expression.action,"Mapped")&&IsDeferred(expression.parameters[1])&&guard_exports.IsEqual(expression.parameters[1].action,"KeyOf")&&IsRef(expression.parameters[1].parameters[0])?[...result,expression.parameters[1].parameters[0].$ref]:result}function BuildDistributionArray(parameters,names){return parameters.reduce((result,left)=>[...result,names.includes(left.name)],[])}function ZipDistributionArray(arguments_,distributionArray,result=[]){return guard_exports.ShiftLeft(arguments_,(argumentLeft,argumentRight)=>guard_exports.ShiftLeft(distributionArray,(booleanLeft,booleanRight)=>ZipDistributionArray(argumentRight,booleanRight,[...result,[booleanLeft,argumentLeft]]),()=>result),()=>result)}function CanonicalArgument(type){return IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsEnum(type)?EvaluateEnum(type.enum):type}function Expand(type){let canonicalArgument=CanonicalArgument(type);return IsUnion(canonicalArgument)?[...canonicalArgument.anyOf]:[canonicalArgument]}function Append(current,type){return current.reduce((result,left)=>[...result,[...left,type]],[])}function Cross(current,variants){return variants.reduce((result,left)=>[...result,...Append(current,left)],[])}function Distribute2(zipped){return zipped.reduce((result,left)=>guard_exports.IsEqual(left[0],!0)?Cross(result,Expand(left[1])):Cross(result,[left[1]]),[[]])}function DistributeArguments(parameters,arguments_,expression){let distributionNames=CollectDistributionNames(expression),distributionArray=BuildDistributionArray(parameters,distributionNames),zippedArguments=ZipDistributionArray(arguments_,distributionArray);return IsDeferred(expression)&&guard_exports.IsEqual(expression.action,"Conditional")||IsDeferred(expression)&&guard_exports.IsEqual(expression.action,"Mapped")?Distribute2(zippedArguments):[arguments_]}function FromNotResolvable(){return["(not-resolvable)",Never()]}function FromNotGeneric(){return["(not-generic)",Never()]}function FromGeneric(name,parameters,expression){return[name,Generic(parameters,expression)]}function FromRef4(context,ref,arguments_){return ref in context?FromType6(context,ref,context[ref],arguments_):FromNotResolvable()}function FromType6(context,name,target,arguments_){return IsGeneric(target)?FromGeneric(name,target.parameters,target.expression):IsRef(target)?FromRef4(context,target.$ref,arguments_):FromNotGeneric()}function ResolveTarget(context,target,arguments_){return FromType6(context,"(anonymous)",target,arguments_)}function AssertArgumentExtends(name,type,extends_){if(IsInfer(type)||IsCall(type)||result_exports.IsExtendsTrueLike(Extends({},type,extends_)))return;let cause={parameter:name,expect:extends_,actual:type};throw new Error(`Argument for parameter ${name} does not satisfy constraint`,{cause})}function BindArgument(context,state,name,extends_,type){let instantiatedArgument=InstantiateType(context,state,type);return AssertArgumentExtends(name,instantiatedArgument,extends_),memory_exports.Assign(context,{[name]:instantiatedArgument})}function BindArguments(context,state,parameterLeft,parameterRight,arguments_){let instantiatedExtends=InstantiateType(context,state,parameterLeft.extends),instantiatedEquals=InstantiateType(context,state,parameterLeft.equals);return guard_exports.ShiftLeft(arguments_,(left,right)=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,left),state,parameterRight,right),()=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,instantiatedEquals),state,parameterRight,[]))}function BindParameters(context,state,parameters,arguments_){return guard_exports.ShiftLeft(parameters,(left,right)=>BindArguments(context,state,left,right,arguments_),()=>context)}function ResolveArgumentsContext(context,state,parameters,arguments_){return BindParameters(context,state,parameters,arguments_)}var instantiationDepth=0,instantiationCount=0;function InstantiationAssert(){if(!guard_exports.IsLessThan(instantiationCount,settings_exports.Get().maxInstantiationCount))throw Error("Type instantiation is excessively deep and possibly infinite")}function InstantiationIncrement(){InstantiationAssert(),instantiationCount++,instantiationDepth++}function InstantiationDecrement(){instantiationDepth--,guard_exports.IsEqual(instantiationDepth,0)&&(instantiationCount=0)}function Peek(state){return guard_exports.IsGreaterThan(state.callstack.length,0)?state.callstack[state.callstack.length-1]:""}function IsTailCall(state,name){return guard_exports.IsEqual(Peek(state),name)}function CallDispatch(context,state,target,parameters,expression,arguments_){InstantiationIncrement();try{let argumentsContext=ResolveArgumentsContext(context,state,parameters,arguments_),returnType=InstantiateType(argumentsContext,State([...state.callstack,target.$ref],state.visited),expression);return InstantiateType(argumentsContext,State([],[]),returnType)}finally{InstantiationDecrement()}}function CallDistributed(context,state,target,parameters,expression,distributedArguments){return distributedArguments.reduce((result,arguments_)=>{let returnType=CallDispatch(context,state,target,parameters,expression,arguments_);return[...result,returnType]},[])}function CallImmediate(context,state,target,parameters,expression,arguments_){let distributedArguments=DistributeArguments(parameters,arguments_,expression),returnTypes=CallDistributed(context,state,target,parameters,expression,distributedArguments);return guard_exports.IsEqual(returnTypes.length,1)?returnTypes[0]:EvaluateUnion(returnTypes)}function CallInstantiate(context,state,target,arguments_){let instantiatedArguments=InstantiateTypes(context,state,arguments_),resolved=ResolveTarget(context,target,arguments_),name=resolved[0],type=resolved[1];return IsGeneric(type)?IsTailCall(state,name)?CallConstruct(Ref(name),instantiatedArguments):CallImmediate(context,state,Ref(name),type.parameters,type.expression,instantiatedArguments):CallConstruct(target,instantiatedArguments)}function CallConstruct(target,arguments_){return memory_exports.Create({"~kind":"Call"},{type:"call",target,arguments:arguments_},{})}function Call2(target,arguments_){return CallInstantiate({},State([],[]),target,arguments_)}function IsCall(value){return IsKind(value,"Call")}function RemoveImmutableOperation(type){return memory_exports.Discard(type,["~immutable"])}function RemoveImmutableAction(type,options2){return memory_exports.Update(RemoveImmutableOperation(type),{},options2)}function RemoveImmutableInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return RemoveImmutableAction(instantiatedType,options2)}function ApplyMapping(mapping,value){return mapping(value)}function FromLiteral3(mapping,value){return guard_exports.IsString(value)?Literal(ApplyMapping(mapping,value)):Literal(value)}function FromTemplateLiteral(mapping,pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType7(mapping,evaluated)}function FromUnion2(mapping,types){let result=types.map(type=>FromType7(mapping,type));return Union(result)}function FromType7(mapping,type){return IsLiteral(type)?FromLiteral3(mapping,type.const):IsTemplateLiteral(type)?FromTemplateLiteral(mapping,type.pattern):IsUnion(type)?FromUnion2(mapping,type.anyOf):type}function CapitalizeDeferred(type,options2={}){return Deferred("Capitalize",[type],options2)}function Capitalize(type,options2={}){return CapitalizeAction(type,options2)}function LowercaseDeferred(type,options2={}){return Deferred("Lowercase",[type],options2)}function Lowercase(type,options2={}){return LowercaseAction(type,options2)}function UncapitalizeDeferred(type,options2={}){return Deferred("Uncapitalize",[type],options2)}function Uncapitalize(type,options2={}){return UncapitalizeAction(type,options2)}function UppercaseDeferred(type,options2={}){return Deferred("Uppercase",[type],options2)}function Uppercase(type,options2={}){return UppercaseAction(type,options2)}var CapitalizeMapping=input=>input[0].toUpperCase()+input.slice(1),LowercaseMapping=input=>input.toLowerCase(),UncapitalizeMapping=input=>input[0].toLowerCase()+input.slice(1),UppercaseMapping=input=>input.toUpperCase();function CapitalizeAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType7(CapitalizeMapping,type),{},options2):CapitalizeDeferred(type,options2)}function LowercaseAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType7(LowercaseMapping,type),{},options2):LowercaseDeferred(type,options2)}function UncapitalizeAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType7(UncapitalizeMapping,type),{},options2):UncapitalizeDeferred(type,options2)}function UppercaseAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType7(UppercaseMapping,type),{},options2):UppercaseDeferred(type,options2)}function CapitalizeInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return CapitalizeAction(instantiatedType,options2)}function LowercaseInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return LowercaseAction(instantiatedType,options2)}function UncapitalizeInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return UncapitalizeAction(instantiatedType,options2)}function UppercaseInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return UppercaseAction(instantiatedType,options2)}function ConditionalDeferred(left,right,true_,false_,options2={}){return Deferred("Conditional",[left,right,true_,false_],options2)}function Conditional(left,right,true_,false_,options2={}){return ConditionalAction({},State([],[]),left,right,true_,false_,options2)}function ConditionalOperation(context,state,left,right,true_,false_){let extendsResult=Extends(context,left,right);return result_exports.IsExtendsUnion(extendsResult)?Union([InstantiateType(extendsResult.inferred,state,true_),InstantiateType(context,state,false_)]):result_exports.IsExtendsTrue(extendsResult)?InstantiateType(extendsResult.inferred,state,true_):InstantiateType(context,state,false_)}function ConditionalAction(context,state,left,right,true_,false_,options2){return CanInstantiate([left,right])?memory_exports.Update(ConditionalOperation(context,state,left,right,true_,false_),{},options2):ConditionalDeferred(left,right,true_,false_,options2)}function ConditionalInstantiate(context,state,left,right,true_,false_,options2){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ConditionalAction(context,state,instantiatedLeft,instantiatedRight,true_,false_,options2)}function ConstructorParametersDeferred(type,options2={}){return Deferred("ConstructorParameters",[type],options2)}function ConstructorParameters(type,options2={}){return ConstructorParametersAction(type,options2)}function ConstructorParametersOperation(type){let parameters=IsConstructor3(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ConstructorParametersAction(type,options2){return CanInstantiate([type])?memory_exports.Update(ConstructorParametersOperation(type),{},options2):ConstructorParametersDeferred(type,options2)}function ConstructorParametersInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return ConstructorParametersAction(instantiatedType,options2)}function ExcludeDeferred(left,right,options2={}){return Deferred("Exclude",[left,right],options2)}function Exclude(left,right,options2={}){return ExcludeAction(left,right,options2)}function ExcludeAction(left,right,options2){return CanInstantiate([left,right])?memory_exports.Update(ExcludeOperation(left,right),{},options2):ExcludeDeferred(left,right,options2)}function ExcludeInstantiate(context,state,left,right,options2){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExcludeAction(instantiatedLeft,instantiatedRight,options2)}function ExtractDeferred(left,right,options2={}){return Deferred("Extract",[left,right],options2)}function Extract(left,right,options2={}){return ExtractAction(left,right,options2)}function ExtractType(left,right){let check=Extends({},left,right);return result_exports.IsExtendsTrueLike(check)?[left]:[]}function ExtractUnion(left,right,result=[]){return guard_exports.ShiftLeft(left,(head,tail)=>ExtractUnion(tail,right,[...result,...ExtractType(head,right)]),()=>result)}function ExtractOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExtractUnion(canonical,right);return EvaluateUnion(remaining)}function ExtractAction(left,right,options2){return CanInstantiate([left,right])?memory_exports.Update(ExtractOperation(left,right),{},options2):ExtractDeferred(left,right,options2)}function ExtractInstantiate(context,state,left,right,options2){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExtractAction(instantiatedLeft,instantiatedRight,options2)}function KeysToLiterals(keys){return keys.reduce((result,left)=>IsLiteralValue(left)?[...result,Literal(left)]:result,[])}function KeysToIndexer(keys){let literals=KeysToLiterals(keys);return Union(literals)}function IndexDeferred(type,indexer,options2={}){return Deferred("Index",[type,indexer],options2)}function Index(type,indexer_or_keys,options2={}){let indexer=guard_exports.IsArray(indexer_or_keys)?KeysToIndexer(indexer_or_keys):indexer_or_keys;return IndexAction(type,indexer,options2)}function FromCyclic(defs,ref){let target=CyclicTarget(defs,ref);return FromType8(target)}function FromDependent(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType8(evaluated)}function CollapseIntersectProperties(left,right){let leftKeys=guard_exports.Keys(left).filter(key=>!guard_exports.HasPropertyKey(right,key)),rightKeys=guard_exports.Keys(right).filter(key=>!guard_exports.HasPropertyKey(left,key)),sharedKeys=guard_exports.Keys(left).filter(key=>guard_exports.HasPropertyKey(right,key)),leftProperties=leftKeys.reduce((result,key)=>({...result,[key]:left[key]}),{}),rightProperties=rightKeys.reduce((result,key)=>({...result,[key]:right[key]}),{}),sharedProperties=sharedKeys.reduce((result,key)=>({...result,[key]:EvaluateIntersect([left[key],right[key]])}),{}),unique=memory_exports.Assign(leftProperties,rightProperties);return memory_exports.Assign(unique,sharedProperties)}function FromIntersect(types){return types.reduce((result,left)=>CollapseIntersectProperties(result,FromType8(left)),{})}function FromTuple(types){let object=TupleToObject(Tuple(types));return FromType8(object)}function CollapseUnionProperties(left,right){return guard_exports.Keys(left).filter(key=>key in right).reduce((result2,key)=>({...result2,[key]:EvaluateUnion([left[key],right[key]])}),{})}function ReduceVariants(types,result){return guard_exports.ShiftLeft(types,(left,right)=>ReduceVariants(right,CollapseUnionProperties(result,FromType8(left))),()=>result)}function FromUnion3(types){return guard_exports.ShiftLeft(types,(left,right)=>ReduceVariants(right,FromType8(left)),()=>Unreachable())}function FromType8(type){return IsCyclic(type)?FromCyclic(type.$defs,type.$ref):IsDependent(type)?FromDependent(type.if,type.then,type.else):IsIntersect(type)?FromIntersect(type.allOf):IsUnion(type)?FromUnion3(type.anyOf):IsTuple(type)?FromTuple(type.items):IsObject3(type)?type.properties:{}}function CollapseToObject(type){let properties=FromType8(type);return _Object_(properties)}var integerKeyPattern=new RegExp("^(?:0|[1-9][0-9]*)$");function ConvertToIntegerKey(value){let normal=`${value}`;return integerKeyPattern.test(normal)?parseInt(normal):value}function NormalizeLiteral(value){return Literal(ConvertToIntegerKey(value))}function NormalizeIndexerTypes(types){return types.map(type=>NormalizeIndexer(type))}function NormalizeIndexer(type){return IsIntersect(type)?Intersect(NormalizeIndexerTypes(type.allOf)):IsUnion(type)?Union(NormalizeIndexerTypes(type.anyOf)):IsLiteral(type)?NormalizeLiteral(type.const):type}function FromArray3(type,indexer){let normalizedIndexer=NormalizeIndexer(indexer),check=Extends({},normalizedIndexer,Number2());return result_exports.IsExtendsTrueLike(check)?type:IsLiteral(indexer)&&guard_exports.IsEqual(indexer.const,"length")?Number2():Never()}function FromCyclic2(defs,ref){let target=CyclicTarget(defs,ref);return FromType9(target)}function FromDependent2(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType9(evaluated)}function FromEnum(values){let evaluated=EvaluateEnum(values);return FromType9(evaluated)}function FromIntersect2(types){let evaluated=EvaluateIntersect(types);return FromType9(evaluated)}function FromLiteral4(value){return[`${value}`]}function FromTemplateLiteral2(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType9(evaluated)}function FromUnion4(types){return types.reduce((result,left)=>[...result,...FromType9(left)],[])}function FromType9(type){return IsCyclic(type)?FromCyclic2(type.$defs,type.$ref):IsDependent(type)?FromDependent2(type.if,type.then,type.else):IsEnum(type)?FromEnum(type.enum):IsIntersect(type)?FromIntersect2(type.allOf):IsLiteral(type)?FromLiteral4(type.const):IsTemplateLiteral(type)?FromTemplateLiteral2(type.pattern):IsUnion(type)?FromUnion4(type.anyOf):[]}function ToIndexableKeys(type){return FromType9(type)}function FromTypes5(properties,types){return types.map(type=>FromType10(properties,type))}function FromType10(properties,type){return IsArray3(type)?_Array_(FromType10(properties,type.items)):IsConstructor3(type)?Constructor(FromTypes5(properties,type.parameters),FromType10(properties,type.instanceType)):IsFunction3(type)?_Function_(FromTypes5(properties,type.parameters),FromType10(properties,type.returnType)):IsTuple(type)?Tuple(FromTypes5(properties,type.items)):IsUnion(type)?Union(FromTypes5(properties,type.anyOf)):IsIntersect(type)?Intersect(FromTypes5(properties,type.allOf)):IsThis(type)?_Object_(properties):type}function ExpandThis(properties,type){return FromType10(properties,type)}function IndexProperty(properties,key){let selectedType=key in properties?properties[key]:Never();return ExpandThis(properties,selectedType)}function IndexProperties(properties,keys){return keys.reduce((result,left)=>[...result,IndexProperty(properties,left)],[])}function FromIndexer(properties,indexer){let keys=ToIndexableKeys(indexer),variants=IndexProperties(properties,keys);return EvaluateUnion(variants)}var NumericKeyPattern=new RegExp(IntegerKey);function NumericKeys(keys){return keys.filter(key=>NumericKeyPattern.test(key))}function FromIndexerNumber(properties){let keys=PropertyKeys(properties),numericKeys=NumericKeys(keys),variants=IndexProperties(properties,numericKeys);return EvaluateUnion(variants)}function FromObject5(properties,indexer){return IsNumber4(indexer)?FromIndexerNumber(properties):FromIndexer(properties,indexer)}function ConvertLiteral(value){return Literal(ConvertToIntegerKey(value))}function ArrayIndexerTypes(types){return types.map(type=>FormatArrayIndexer(type))}function FormatArrayIndexer(type){return IsIntersect(type)?Intersect(ArrayIndexerTypes(type.allOf)):IsUnion(type)?Union(ArrayIndexerTypes(type.anyOf)):IsLiteral(type)?ConvertLiteral(type.const):type}function IndexElementsWithIndexer(types,indexer){return types.reduceRight((result,right,index)=>{let check=Extends({},Literal(index),indexer);return result_exports.IsExtendsTrueLike(check)?[right,...result]:result},[])}function FromTupleWithIndexer(types,indexer){let formattedArrayIndexer=FormatArrayIndexer(indexer),elements=IndexElementsWithIndexer(types,formattedArrayIndexer);return EvaluateUnionFast(elements)}function FromTupleWithoutIndexer(types){return EvaluateUnionFast(types)}function FromTuple2(types,indexer){return IsLiteral(indexer)&&guard_exports.IsEqual(indexer.const,"length")?Literal(types.length):IsNumber4(indexer)||IsInteger3(indexer)?FromTupleWithoutIndexer(types):FromTupleWithIndexer(types,indexer)}function FromType11(type,indexer){return IsArray3(type)?FromArray3(type.items,indexer):IsObject3(type)?FromObject5(type.properties,indexer):IsTuple(type)?FromTuple2(type.items,indexer):Never()}function NormalizeType(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function IndexAction(type,indexer,options2){return CanInstantiate([type,indexer])?memory_exports.Update(FromType11(NormalizeType(type),indexer),{},options2):IndexDeferred(type,indexer,options2)}function IndexInstantiate(context,state,type,indexer,options2){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return IndexAction(instantiatedType,instantiatedIndexer,options2)}function InstanceTypeDeferred(type,options2={}){return Deferred("InstanceType",[type],options2)}function InstanceType(type,options2={}){return InstanceTypeAction(type,options2)}function InstanceTypeOperation(type){return IsConstructor3(type)?type.instanceType:Never()}function InstanceTypeAction(type,options2){return CanInstantiate([type])?memory_exports.Update(InstanceTypeOperation(type),{},options2):InstanceTypeDeferred(type,options2)}function InstanceTypeInstantiate(context,state,type,options2={}){let instantiatedType=InstantiateType(context,state,type);return InstanceTypeAction(instantiatedType,options2)}function KeyOfDeferred(type,options2={}){return Deferred("KeyOf",[type],options2)}function KeyOf2(type,options2={}){return KeyOfAction(type,options2)}function FromAny(){return Union([Number2(),String2(),Symbol2()])}function FromArray4(_type){return Number2()}function FromPropertyKeys(keys){return keys.reduce((result2,left)=>IsLiteralValue(left)?[...result2,Literal(ConvertToIntegerKey(left))]:Unreachable(),[])}function FromObject6(properties){let propertyKeys=guard_exports.Keys(properties),variants=FromPropertyKeys(propertyKeys);return EvaluateUnionFast(variants)}function FromRecord2(type){return RecordKey(type)}function FromTuple3(types){let result=types.map((_,index)=>Literal(index));return EvaluateUnionFast(result)}function FromType12(type){return IsAny(type)?FromAny():IsArray3(type)?FromArray4(type.items):IsObject3(type)?FromObject6(type.properties):IsRecord(type)?FromRecord2(type):IsTuple(type)?FromTuple3(type.items):Never()}function NormalizeType2(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function KeyOfAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType12(NormalizeType2(type)),{},options2):KeyOfDeferred(type,options2)}function KeyOfInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return KeyOfAction(instantiatedType,options2)}function MappedDeferred(identifier,type,as,property,options2={}){return Deferred("Mapped",[identifier,type,as,property],options2)}function Mapped(identifier,type,as,property,options2={}){return MappedAction({},State([],[]),identifier,type,as,property,options2)}function FromTemplateLiteral3(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType13(evaluated)}function FromUnion5(types){return types.reduce((result,left)=>[...result,...FromType13(left)],[])}function FromEnum2(values){let evaluated=EvaluateEnum(values);return FromType13(evaluated)}function FromLiteral5(value){return guard_exports.IsNumber(value)?[Literal(`${value}`)]:[Literal(value)]}function FromType13(type){return IsEnum(type)?FromEnum2(type.enum):IsLiteral(type)?FromLiteral5(type.const):IsTemplateLiteral(type)?FromTemplateLiteral3(type.pattern):IsUnion(type)?FromUnion5(type.anyOf):[type]}function MappedVariants(type){return FromType13(type)}function CanonicalAs(instantiatedAs){return IsTemplateLiteral(instantiatedAs)?EvaluateTemplateLiteral(instantiatedAs.pattern):instantiatedAs}function MappedVariant(context,state,identifier,variant,as,property){let variantContext=memory_exports.Assign(context,{[identifier.name]:variant}),instantiatedAs=InstantiateType(variantContext,state,as),canonicalAs=CanonicalAs(instantiatedAs),instantiatedProperty=InstantiateType(variantContext,state,property);return IsLiteralNumber(canonicalAs)||IsLiteralString(canonicalAs)?{[canonicalAs.const]:instantiatedProperty}:{}}function MappedProperties(context,state,identifier,variants,as,property){return variants.reduce((result,left)=>[...result,MappedVariant(context,state,identifier,left,as,property)],[])}function MappedObjects(properties){return properties.reduce((result,left)=>[...result,_Object_(left)],[])}function MappedOperation(context,state,identifier,type,as,property){let variants=MappedVariants(type),mappedProperties=MappedProperties(context,state,identifier,variants,as,property),mappedObjects=MappedObjects(mappedProperties);return EvaluateIntersect(mappedObjects)}function MappedAction(context,state,identifier,type,as,property,options2){return CanInstantiate([type])?memory_exports.Update(MappedOperation(context,state,identifier,type,as,property),{},options2):MappedDeferred(identifier,type,as,property,options2)}function MappedInstantiate(context,state,identifier,type,as,property,options2){let instantiatedType=InstantiateType(context,state,type);return MappedAction(context,state,identifier,instantiatedType,as,property,options2)}function InstantiateCyclics(context,declarations,cyclicKeys){let declarationContext=memory_exports.Assign(context,declarations);return guard_exports.Keys(declarations).filter(key=>cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateCyclic(declarationContext,key,declarations[key])}),{})}function InstantiateNonCyclics(context,declarations,cyclicKeys){let declarationContext=memory_exports.Assign(context,declarations);return guard_exports.Keys(declarations).filter(key=>!cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateType(declarationContext,State([],[]),declarations[key])}),{})}function InstantiateModule(context,declarations,options2){let cyclicCandidates=CyclicCandidates(declarations),instantiatedCyclics=InstantiateCyclics(context,declarations,cyclicCandidates),instantiatedNonCyclics=InstantiateNonCyclics(context,declarations,cyclicCandidates),instantiatedModule={...instantiatedCyclics,...instantiatedNonCyclics};return memory_exports.Update(instantiatedModule,{},options2)}function ModuleInstantiate(context,_state,declarations,options2){return InstantiateModule(context,declarations,options2)}function NonNullableDeferred(type,options2={}){return Deferred("NonNullable",[type],options2)}function NonNullable(type,options2={}){return NonNullableAction(type,options2)}function NonNullableOperation(type){let excluded=Union([Null(),Undefined()]);return ExcludeAction(type,excluded,{})}function NonNullableAction(type,options2){return CanInstantiate([type])?memory_exports.Update(NonNullableOperation(type),{},options2):NonNullableDeferred(type,options2)}function NonNullableInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return NonNullableAction(instantiatedType,options2)}function OmitDeferred(type,indexer,options2={}){return Deferred("Omit",[type,indexer],options2)}function Omit(type,indexer_or_keys,options2={}){let indexer=guard_exports.IsArray(indexer_or_keys)?KeysToIndexer(indexer_or_keys):indexer_or_keys;return OmitAction(type,indexer,options2)}function ToIndexable(type){let collapsed=CollapseToObject(type);return IsObject3(collapsed)?collapsed.properties:Unreachable()}function FromKeys(properties,keys){return guard_exports.Keys(properties).reduce((result2,key)=>keys.includes(key)?result2:{...result2,[key]:properties[key]},{})}function FromType14(type,indexer){let indexable=ToIndexable(type),indexableKeys=ToIndexableKeys(indexer),omitted=FromKeys(indexable,indexableKeys);return _Object_(omitted)}function OmitAction(type,indexer,options2){return CanInstantiate([type,indexer])?memory_exports.Update(FromType14(type,indexer),{},options2):OmitDeferred(type,indexer,options2)}function OmitInstantiate(context,state,type,indexer,options2){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return OmitAction(instantiatedType,instantiatedIndexer,options2)}function ParametersDeferred(type,options2={}){return Deferred("Parameters",[type],options2)}function Parameters(type,options2={}){return ParametersAction(type,options2)}function ParametersOperation(type){let parameters=IsFunction3(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ParametersAction(type,options2){return CanInstantiate([type])?memory_exports.Update(ParametersOperation(type),{},options2):ParametersDeferred(type,options2)}function ParametersInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return ParametersAction(instantiatedType,options2)}function PartialDeferred(type,options2={}){return Deferred("Partial",[type],options2)}function Partial(type,options2={}){return PartialAction(type,options2)}function FromCyclic3(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType15(target);return Cyclic(memory_exports.Assign(defs,{[ref]:partial}),ref)}function FromDependent3(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType15(evaluated)}function FromIntersect3(types){let evaluated=EvaluateIntersect(types);return FromType15(evaluated)}function FromUnion6(types){let result=types.map(type=>FromType15(type));return Union(result)}function FromObject7(properties){let mapped=guard_exports.Keys(properties).reduce((result2,left)=>({...result2,[left]:AddOptional(properties[left])}),{});return _Object_(mapped)}function FromType15(type){return IsCyclic(type)?FromCyclic3(type.$defs,type.$ref):IsDependent(type)?FromDependent3(type.if,type.then,type.else):IsIntersect(type)?FromIntersect3(type.allOf):IsUnion(type)?FromUnion6(type.anyOf):IsObject3(type)?FromObject7(type.properties):_Object_({})}function PartialAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType15(type),{},options2):PartialDeferred(type,options2)}function PartialInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return PartialAction(instantiatedType,options2)}function PickDeferred(type,indexer,options2={}){return Deferred("Pick",[type,indexer],options2)}function Pick(type,indexer_or_keys,options2={}){let indexer=guard_exports.IsArray(indexer_or_keys)?KeysToIndexer(indexer_or_keys):indexer_or_keys;return PickAction(type,indexer,options2)}function FromKeys2(properties,keys){return guard_exports.Keys(properties).reduce((result2,key)=>keys.includes(key)?memory_exports.Assign(result2,{[key]:properties[key]}):result2,{})}function FromType16(type,indexer){let indexable=ToIndexable(type),keys=ToIndexableKeys(indexer),applied=FromKeys2(indexable,keys);return _Object_(applied)}function PickAction(type,indexer,options2){return CanInstantiate([type,indexer])?memory_exports.Update(FromType16(type,indexer),{},options2):PickDeferred(type,indexer,options2)}function PickInstantiate(context,state,type,indexer,options2){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return PickAction(instantiatedType,instantiatedIndexer,options2)}function ReadonlyObjectDeferred(type,options2={}){return Deferred("ReadonlyObject",[type],options2)}function ReadonlyObject(type,options2={}){return ReadonlyObjectAction(type,options2)}var ReadonlyType=ReadonlyObject;function FromArray5(type){return AddImmutable(_Array_(type))}function FromCyclic4(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType17(target);return Cyclic(memory_exports.Assign(defs,{[ref]:partial}),ref)}function FromDependent4(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType17(evaluated)}function FromIntersect4(types){let evaluated=EvaluateIntersect(types);return FromType17(evaluated)}function FromObject8(properties){let mapped=guard_exports.Keys(properties).reduce((result2,left)=>({...result2,[left]:AddReadonly(properties[left])}),{});return _Object_(mapped)}function FromTuple4(types){return AddImmutable(Tuple(types))}function FromUnion7(types){let result=types.map(type=>FromType17(type));return Union(result)}function FromType17(type){return IsArray3(type)?FromArray5(type.items):IsCyclic(type)?FromCyclic4(type.$defs,type.$ref):IsDependent(type)?FromDependent4(type.if,type.then,type.else):IsIntersect(type)?FromIntersect4(type.allOf):IsObject3(type)?FromObject8(type.properties):IsTuple(type)?FromTuple4(type.items):IsUnion(type)?FromUnion7(type.anyOf):type}function ReadonlyObjectAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType17(type),{},options2):ReadonlyObjectDeferred(type)}function ReadonlyObjectInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return ReadonlyObjectAction(instantiatedType,options2)}function RefInstantiate(context,state,type,ref){return state.visited.includes(ref)?type:ref in context?InstantiateType(context,State(state.callstack,[...state.visited,ref]),context[ref]):type}function FromCyclic5(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType18(target);return Cyclic(memory_exports.Assign(defs,{[ref]:partial}),ref)}function FromDependent5(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType18(evaluated)}function FromIntersect5(types){let evaluated=EvaluateIntersect(types);return FromType18(evaluated)}function FromUnion8(types){let result=types.map(type=>FromType18(type));return Union(result)}function FromObject9(properties){let mapped=guard_exports.Keys(properties).reduce((result2,left)=>({...result2,[left]:RemoveOptional(properties[left])}),{});return _Object_(mapped)}function FromType18(type){return IsCyclic(type)?FromCyclic5(type.$defs,type.$ref):IsDependent(type)?FromDependent5(type.if,type.then,type.else):IsIntersect(type)?FromIntersect5(type.allOf):IsUnion(type)?FromUnion8(type.anyOf):IsObject3(type)?FromObject9(type.properties):_Object_({})}function RequiredDeferred(type,options2={}){return Deferred("Required",[type],options2)}function Required(type,options2={}){return RequiredAction(type,options2)}function RequiredAction(type,options2){return CanInstantiate([type])?memory_exports.Update(FromType18(type),{},options2):RequiredDeferred(type,options2)}function RequiredInstantiate(context,state,type,options2){let instaniatedType=InstantiateType(context,state,type);return RequiredAction(instaniatedType,options2)}function ReturnTypeDeferred(type,options2={}){return Deferred("ReturnType",[type],options2)}function ReturnType(type,options2={}){return ReturnTypeAction(type,options2)}function ReturnTypeOperation(type){return IsFunction3(type)?type.returnType:Never()}function ReturnTypeAction(type,options2){return CanInstantiate([type])?memory_exports.Update(ReturnTypeOperation(type),{},options2):ReturnTypeDeferred(type,options2)}function ReturnTypeInstantiate(context,state,type,options2={}){let instantiatedType=InstantiateType(context,state,type);return ReturnTypeAction(instantiatedType,options2)}function WithDeferred(type,options2){return Deferred("With",[type,options2],{})}function With2(type,options2){return WithAction(type,options2)}function WithAction(type,options2){return CanInstantiate([type])?memory_exports.Update(type,{},options2):WithDeferred(type,options2)}function WithInstantiate(context,state,type,options2){let instaniatedType=InstantiateType(context,state,type);return WithAction(instaniatedType,options2)}function SpreadElement(type){return IsRest(type)?IsTuple(type.items)?RestSpread(type.items.items):IsInfer(type.items)?[type]:IsRef(type.items)?[type]:[Never()]:[type]}function RestSpread(types){return types.reduce((result2,left)=>[...result2,...SpreadElement(left)],[])}function State(callstack,visited){return{callstack,visited}}function CanInstantiate(types){return guard_exports.ShiftLeft(types,(left,right)=>IsRef(left)?!1:CanInstantiate(right),()=>!0)}function InstantiateProperties(context,state,properties){return guard_exports.Keys(properties).reduce((result,key)=>({...result,[key]:InstantiateType(context,state,properties[key])}),{})}function InstantiateElements(context,state,types){let elements=InstantiateTypes(context,state,types);return RestSpread(elements)}function InstantiateTypes(context,state,types){return types.map(type=>InstantiateType(context,state,type))}function WithModifiers(type,instantiatedType){let withOptional=IsOptional(type)?AddOptionalAction(instantiatedType,{}):instantiatedType,withReadonly=IsReadonly(type)?AddReadonlyAction(withOptional,{}):withOptional;return IsImmutable(type)?AddImmutableAction(withReadonly,{}):withReadonly}function InstantiateDeferred(context,state,action,parameters,options2){return guard_exports.IsEqual(action,"AddImmutable")?AddImmutableInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"RemoveImmutable")?RemoveImmutableInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"AddReadonly")?AddReadonlyInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"RemoveReadonly")?RemoveReadonlyInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"AddOptional")?AddOptionalInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"RemoveOptional")?RemoveOptionalInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Capitalize")?CapitalizeInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Conditional")?ConditionalInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options2):guard_exports.IsEqual(action,"ConstructorParameters")?ConstructorParametersInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Evaluate")?EvaluateInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Exclude")?ExcludeInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"Extract")?ExtractInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"Index")?IndexInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"InstanceType")?InstanceTypeInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Interface")?InterfaceInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"KeyOf")?KeyOfInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Lowercase")?LowercaseInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Mapped")?MappedInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options2):guard_exports.IsEqual(action,"Module")?ModuleInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"NonNullable")?NonNullableInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Pick")?PickInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"Parameters")?ParametersInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Partial")?PartialInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Omit")?OmitInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"ReadonlyObject")?ReadonlyObjectInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Record")?RecordInstantiate(context,state,parameters[0],parameters[1],options2):guard_exports.IsEqual(action,"Required")?RequiredInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"ReturnType")?ReturnTypeInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"TemplateLiteral")?TemplateLiteralInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Uncapitalize")?UncapitalizeInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"Uppercase")?UppercaseInstantiate(context,state,parameters[0],options2):guard_exports.IsEqual(action,"With")?WithInstantiate(context,state,parameters[0],parameters[1]):Deferred(action,parameters,options2)}function InstantiateImmediate(context,state,type){let instantiatedType=IsRef(type)?RefInstantiate(context,state,type,type.$ref):IsArray3(type)?_Array_(InstantiateType(context,state,type.items),ArrayOptions(type)):IsCall(type)?CallInstantiate(context,state,type.target,type.arguments):IsConstructor3(type)?Constructor(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.instanceType),ConstructorOptions(type)):IsFunction3(type)?_Function_(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.returnType),FunctionOptions(type)):IsDependent(type)?Dependent(InstantiateType(context,state,type.if),InstantiateType(context,state,type.then),InstantiateType(context,state,type.else),DependentOptions(type)):IsIntersect(type)?Intersect(InstantiateTypes(context,state,type.allOf),IntersectOptions(type)):IsObject3(type)?_Object_(InstantiateProperties(context,state,type.properties),ObjectOptions(type)):IsRecord(type)?RecordFromPattern(RecordPattern(type),InstantiateType(context,state,RecordValue(type))):IsRest(type)?Rest(InstantiateType(context,state,type.items)):IsTuple(type)?Tuple(InstantiateElements(context,state,type.items),TupleOptions(type)):IsUnion(type)?Union(InstantiateTypes(context,state,type.anyOf),UnionOptions(type)):type;return WithModifiers(type,instantiatedType)}function InstantiateType(context,state,type){return IsDeferred(type)?InstantiateDeferred(context,state,type.action,type.parameters,type.options):InstantiateImmediate(context,state,type)}function Instantiate(context,type){return InstantiateType(context,State([],[]),type)}function AddImmutableOperation(type){return memory_exports.Update(type,{"~immutable":!0},{})}function AddImmutableAction(type,options2){return memory_exports.Update(AddImmutableOperation(type),{},options2)}function AddImmutableInstantiate(context,state,type,options2){let instantiatedType=InstantiateType(context,state,type);return AddImmutableAction(instantiatedType,options2)}function AddImmutableDeferred(type,options2={}){return Deferred("AddImmutable",[type],options2)}function AddImmutable(type,options2={}){return AddImmutableAction(type,options2)}function RemoveImmutableDeferred(type,options2={}){return Deferred("RemoveImmutable",[type],options2)}function RemoveImmutable(type,options2={}){return RemoveImmutableAction(type,options2)}function EvaluateDeferred(type,options2={}){return Deferred("Evaluate",[type],options2)}function Evaluate2(type,options2={}){return EvaluateAction(type,options2)}function ModuleDeferred(declarations,options2={}){return Deferred("Module",[declarations],options2)}function Module2(declarations,options2={}){return ModuleInstantiate({},State([],[]),declarations,options2)}function Comparer(left,right){let compareResult=Compare(left,right);return guard_exports.IsEqual(compareResult,CompareResultRightInside)||guard_exports.IsEqual(compareResult,CompareResultDisjoint)?1:0}function Insert(type,types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>guard_exports.IsEqual(Comparer(type,left),1)?Insert(type,right,[...result,left]):[...result,type,...types],()=>[...result,type])}function Sort(types,result=[]){return guard_exports.ShiftLeft(types,(left,right)=>Sort(right,Insert(left,result)),()=>result)}function Priority(types){return Sort(types)}function IsTemplateLiteralPattern(pattern){let types=ParsePatternIntoTypes(pattern);return!guard_exports.IsEqual(types.length,0)}function Script2(...args){let[context,input,options2]=arguments_exports.Match(args,{2:(script,options3)=>guard_exports.IsString(script)?[{},script,options3]:[script,options3,{}],3:(context2,script,options3)=>[context2,script,options3],1:script=>[{},script,{}]}),result=Script(input),parsed=guard_exports.IsArray(result)&&guard_exports.IsEqual(result.length,2)?InstantiateType(context,State([],[]),result[0]):Never();return memory_exports.Update(parsed,{},options2)}var typebox_exports={};__export(typebox_exports,{Any:()=>Any,Array:()=>_Array_,BigInt:()=>BigInt2,Boolean:()=>Boolean2,Call:()=>Call2,Capitalize:()=>Capitalize,Codec:()=>Codec,Conditional:()=>Conditional,Constructor:()=>Constructor,ConstructorParameters:()=>ConstructorParameters,Cyclic:()=>Cyclic,Decode:()=>Decode,DecodeBuilder:()=>DecodeBuilder,Dependent:()=>Dependent,Encode:()=>Encode,EncodeBuilder:()=>EncodeBuilder,Enum:()=>Enum,Evaluate:()=>Evaluate2,Exclude:()=>Exclude,Extends:()=>Extends,ExtendsResult:()=>result_exports,Extract:()=>Extract,Function:()=>_Function_,Generic:()=>Generic,Identifier:()=>Identifier,Immutable:()=>Immutable,Index:()=>Index,Infer:()=>Infer,InstanceType:()=>InstanceType,Instantiate:()=>Instantiate,Integer:()=>Integer,Interface:()=>Interface,Intersect:()=>Intersect,IsAny:()=>IsAny,IsArray:()=>IsArray3,IsBigInt:()=>IsBigInt3,IsBoolean:()=>IsBoolean4,IsCall:()=>IsCall,IsCodec:()=>IsCodec,IsConstructor:()=>IsConstructor3,IsCyclic:()=>IsCyclic,IsDependent:()=>IsDependent,IsEnum:()=>IsEnum,IsEnumValue:()=>IsEnumValue,IsFunction:()=>IsFunction3,IsGeneric:()=>IsGeneric,IsIdentifier:()=>IsIdentifier2,IsImmutable:()=>IsImmutable,IsInfer:()=>IsInfer,IsInteger:()=>IsInteger3,IsIntersect:()=>IsIntersect,IsKind:()=>IsKind,IsLiteral:()=>IsLiteral,IsNever:()=>IsNever,IsNull:()=>IsNull3,IsNumber:()=>IsNumber4,IsObject:()=>IsObject3,IsOptional:()=>IsOptional,IsParameter:()=>IsParameter,IsReadonly:()=>IsReadonly,IsRecord:()=>IsRecord,IsRef:()=>IsRef,IsRefine:()=>IsRefine,IsRest:()=>IsRest,IsSchema:()=>IsSchema,IsString:()=>IsString4,IsSymbol:()=>IsSymbol3,IsTemplateLiteral:()=>IsTemplateLiteral,IsThis:()=>IsThis,IsTuple:()=>IsTuple,IsUndefined:()=>IsUndefined3,IsUnion:()=>IsUnion,IsUnknown:()=>IsUnknown,IsUnsafe:()=>IsUnsafe,IsVoid:()=>IsVoid,KeyOf:()=>KeyOf2,Literal:()=>Literal,Lowercase:()=>Lowercase,Mapped:()=>Mapped,Module:()=>Module2,Never:()=>Never,NonNullable:()=>NonNullable,Null:()=>Null,Number:()=>Number2,Object:()=>_Object_,Omit:()=>Omit,Optional:()=>Optional,Parameter:()=>Parameter,Parameters:()=>Parameters,Partial:()=>Partial,Pick:()=>Pick,Readonly:()=>Readonly,ReadonlyObject:()=>ReadonlyObject,ReadonlyType:()=>ReadonlyType,Record:()=>Record,RecordKey:()=>RecordKey,RecordPattern:()=>RecordPattern,RecordValue:()=>RecordValue,Ref:()=>Ref,Refine:()=>Refine,Required:()=>Required,Rest:()=>Rest,ReturnType:()=>ReturnType,Script:()=>Script2,String:()=>String2,Symbol:()=>Symbol2,TemplateLiteral:()=>TemplateLiteral2,This:()=>This,Tuple:()=>Tuple,Uncapitalize:()=>Uncapitalize,Undefined:()=>Undefined,Union:()=>Union,Unknown:()=>Unknown,Unsafe:()=>Unsafe,Uppercase:()=>Uppercase,Void:()=>Void,With:()=>With2});var build_default=typebox_exports;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:()=>Marked,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,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,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,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,resetCapabilitiesCache:()=>resetCapabilitiesCache,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 _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}var noopTest={exec:()=>null};function edit(regex,opt=""){let source=typeof regex=="string"?regex:regex.source,obj={replace:(name,val)=>{let valSource=typeof val=="string"?val:val.source;return valSource=valSource.replace(other.caret,"$1"),source=source.replace(name,valSource),obj},getRegex:()=>new RegExp(source,opt)};return obj}var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ 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,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,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,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),htmlBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i")},newline=/^(?:[ \t]*(?:\n|$))+/,blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lheading=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="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|ul",_comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).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+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^
9
- ]`).replace("lheading",lheading).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},escape=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,inlineCode=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br=/^( {2,}|\\)\n(?!\s*$)/,inlineText=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_punctuation=/[\p{P}\p{S}]/u,_punctuationOrSpace=/[\s\p{P}\p{S}]/u,_notPunctuationOrSpace=/[^\s\p{P}\p{S}]/u,punctuation=edit(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_punctuationOrSpace).getRegex(),_punctuationGfmStrongEm=/(?!~)[\p{P}\p{S}]/u,_punctuationOrSpaceGfmStrongEm=/(?!~)[\s\p{P}\p{S}]/u,_notPunctuationOrSpaceGfmStrongEm=/(?:[^\s\p{P}\p{S}]|~)/u,blockSkip=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,emStrongLDelimCore=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,emStrongLDelim=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuation).getRegex(),emStrongLDelimGfm=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimAstCore="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",emStrongRDelimAst=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),emStrongRDelimAstGfm=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g,_punctuationOrSpaceGfmStrongEm).replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimUnd=edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),anyPunctuation=edit(/\\(punct)/,"gu").replace(/punct/g,_punctuation).getRegex(),autolink=edit(/^<(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(),_inlineComment=edit(_comment).replace("(?:-->|$)","-->").getRegex(),tag=edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_inlineComment).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_inlineLabel=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,link=edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",_inlineLabel).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),reflink=edit(/^!?\[(label)\]\[(ref)\]/).replace("label",_inlineLabel).replace("ref",_blockLabel).getRegex(),nolink=edit(/^!?\[(ref)\](?:\[\])?/).replace("ref",_blockLabel).getRegex(),reflinkSearch=edit("reflink|nolink(?!\\()","g").replace("reflink",reflink).replace("nolink",nolink).getRegex(),inlineNormal={_backpedal:noopTest,anyPunctuation,autolink,blockSkip,br,code:inlineCode,del:noopTest,emStrongLDelim,emStrongRDelimAst,emStrongRDelimUnd,escape,link,nolink,punctuation,reflink,reflinkSearch,tag,text:inlineText,url:noopTest},inlinePedantic={...inlineNormal,link:edit(/^!?\[(label)\]\((.*?)\)/).replace("label",_inlineLabel).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_inlineLabel).getRegex()},inlineGfm={...inlineNormal,emStrongRDelimAst:emStrongRDelimAstGfm,emStrongLDelim:emStrongLDelimGfm,url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},inlineBreaks={...inlineGfm,br:edit(br).replace("{2,}","*").getRegex(),text:edit(inlineGfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},block={normal:blockNormal,gfm:blockGfm,pedantic:blockPedantic},inline={normal:inlineNormal,gfm:inlineGfm,breaks:inlineBreaks,pedantic:inlinePedantic},escapeReplacements={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},getEscapeReplacement=ch=>escapeReplacements[ch];function escape2(html2,encode){if(encode){if(other.escapeTest.test(html2))return html2.replace(other.escapeReplace,getEscapeReplacement)}else if(other.escapeTestNoEncode.test(html2))return html2.replace(other.escapeReplaceNoEncode,getEscapeReplacement);return html2}function cleanUrl(href){try{href=encodeURI(href).replace(other.percentDecode,"%")}catch{return null}return href}function splitCells(tableRow,count){let row=tableRow.replace(other.findPipe,(match,offset,str2)=>{let escaped=!1,curr=offset;for(;--curr>=0&&str2[curr]==="\\";)escaped=!escaped;return escaped?"|":" |"}),cells=row.split(other.splitPipe),i=0;if(cells[0].trim()||cells.shift(),cells.length>0&&!cells.at(-1)?.trim()&&cells.pop(),count)if(cells.length>count)cells.splice(count);else for(;cells.length<count;)cells.push("");for(;i<cells.length;i++)cells[i]=cells[i].trim().replace(other.slashPipe,"|");return cells}function rtrim(str2,c2,invert){let l=str2.length;if(l===0)return"";let suffLen=0;for(;suffLen<l;){let currChar=str2.charAt(l-suffLen-1);if(currChar===c2&&!invert)suffLen++;else if(currChar!==c2&&invert)suffLen++;else break}return str2.slice(0,l-suffLen)}function findClosingBracket(str2,b){if(str2.indexOf(b[1])===-1)return-1;let level=0;for(let i=0;i<str2.length;i++)if(str2[i]==="\\")i++;else if(str2[i]===b[0])level++;else if(str2[i]===b[1]&&(level--,level<0))return i;return level>0?-2:-1}function outputLink(cap,link2,raw,lexer2,rules){let href=link2.href,title=link2.title||null,text=cap[1].replace(rules.other.outputLinkReplace,"$1");lexer2.state.inLink=!0;let token={type:cap[0].charAt(0)==="!"?"image":"link",raw,href,title,text,tokens:lexer2.inlineTokens(text)};return lexer2.state.inLink=!1,token}function indentCodeCompensation(raw,text,rules){let matchIndentToCode=raw.match(rules.other.indentCodeCompensation);if(matchIndentToCode===null)return text;let indentToCode=matchIndentToCode[1];return text.split(`
10
- `).map(node=>{let matchIndentInNode=node.match(rules.other.beginningSpace);if(matchIndentInNode===null)return node;let[indentInNode]=matchIndentInNode;return indentInNode.length>=indentToCode.length?node.slice(indentToCode.length):node}).join(`
11
- `)}var _Tokenizer=class{options;rules;lexer;constructor(options2){this.options=options2||_defaults}space(src){let cap=this.rules.block.newline.exec(src);if(cap&&cap[0].length>0)return{type:"space",raw:cap[0]}}code(src){let cap=this.rules.block.code.exec(src);if(cap){let text=cap[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:cap[0],codeBlockStyle:"indented",text:this.options.pedantic?text:rtrim(text,`
12
- `)}}}fences(src){let cap=this.rules.block.fences.exec(src);if(cap){let raw=cap[0],text=indentCodeCompensation(raw,cap[3]||"",this.rules);return{type:"code",raw,lang:cap[2]?cap[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):cap[2],text}}}heading(src){let cap=this.rules.block.heading.exec(src);if(cap){let text=cap[2].trim();if(this.rules.other.endingHash.test(text)){let trimmed=rtrim(text,"#");(this.options.pedantic||!trimmed||this.rules.other.endingSpaceChar.test(trimmed))&&(text=trimmed.trim())}return{type:"heading",raw:cap[0],depth:cap[1].length,text,tokens:this.lexer.inline(text)}}}hr(src){let cap=this.rules.block.hr.exec(src);if(cap)return{type:"hr",raw:rtrim(cap[0],`
13
- `)}}blockquote(src){let cap=this.rules.block.blockquote.exec(src);if(cap){let lines=rtrim(cap[0],`
14
- `).split(`
15
- `),raw="",text="",tokens=[];for(;lines.length>0;){let inBlockquote=!1,currentLines=[],i;for(i=0;i<lines.length;i++)if(this.rules.other.blockquoteStart.test(lines[i]))currentLines.push(lines[i]),inBlockquote=!0;else if(!inBlockquote)currentLines.push(lines[i]);else break;lines=lines.slice(i);let currentRaw=currentLines.join(`
16
- `),currentText=currentRaw.replace(this.rules.other.blockquoteSetextReplace,`
17
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");raw=raw?`${raw}
18
- ${currentRaw}`:currentRaw,text=text?`${text}
19
- ${currentText}`:currentText;let top=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(currentText,tokens,!0),this.lexer.state.top=top,lines.length===0)break;let lastToken=tokens.at(-1);if(lastToken?.type==="code")break;if(lastToken?.type==="blockquote"){let oldToken=lastToken,newText=oldToken.raw+`
20
- `+lines.join(`
21
- `),newToken=this.blockquote(newText);tokens[tokens.length-1]=newToken,raw=raw.substring(0,raw.length-oldToken.raw.length)+newToken.raw,text=text.substring(0,text.length-oldToken.text.length)+newToken.text;break}else if(lastToken?.type==="list"){let oldToken=lastToken,newText=oldToken.raw+`
22
- `+lines.join(`
23
- `),newToken=this.list(newText);tokens[tokens.length-1]=newToken,raw=raw.substring(0,raw.length-lastToken.raw.length)+newToken.raw,text=text.substring(0,text.length-oldToken.raw.length)+newToken.raw,lines=newText.substring(tokens.at(-1).raw.length).split(`
24
- `);continue}}return{type:"blockquote",raw,tokens,text}}}list(src){let cap=this.rules.block.list.exec(src);if(cap){let bull=cap[1].trim(),isordered=bull.length>1,list2={type:"list",raw:"",ordered:isordered,start:isordered?+bull.slice(0,-1):"",loose:!1,items:[]};bull=isordered?`\\d{1,9}\\${bull.slice(-1)}`:`\\${bull}`,this.options.pedantic&&(bull=isordered?bull:"[*+-]");let itemRegex=this.rules.other.listItemRegex(bull),endsWithBlankLine=!1;for(;src;){let endEarly=!1,raw="",itemContents="";if(!(cap=itemRegex.exec(src))||this.rules.block.hr.test(src))break;raw=cap[0],src=src.substring(raw.length);let line=cap[2].split(`
25
- `,1)[0].replace(this.rules.other.listReplaceTabs,t=>" ".repeat(3*t.length)),nextLine=src.split(`
26
- `,1)[0],blankLine=!line.trim(),indent=0;if(this.options.pedantic?(indent=2,itemContents=line.trimStart()):blankLine?indent=cap[1].length+1:(indent=cap[2].search(this.rules.other.nonSpaceChar),indent=indent>4?1:indent,itemContents=line.slice(indent),indent+=cap[1].length),blankLine&&this.rules.other.blankLine.test(nextLine)&&(raw+=nextLine+`
27
- `,src=src.substring(nextLine.length+1),endEarly=!0),!endEarly){let nextBulletRegex=this.rules.other.nextBulletRegex(indent),hrRegex=this.rules.other.hrRegex(indent),fencesBeginRegex=this.rules.other.fencesBeginRegex(indent),headingBeginRegex=this.rules.other.headingBeginRegex(indent),htmlBeginRegex=this.rules.other.htmlBeginRegex(indent);for(;src;){let rawLine=src.split(`
28
- `,1)[0],nextLineWithoutTabs;if(nextLine=rawLine,this.options.pedantic?(nextLine=nextLine.replace(this.rules.other.listReplaceNesting," "),nextLineWithoutTabs=nextLine):nextLineWithoutTabs=nextLine.replace(this.rules.other.tabCharGlobal," "),fencesBeginRegex.test(nextLine)||headingBeginRegex.test(nextLine)||htmlBeginRegex.test(nextLine)||nextBulletRegex.test(nextLine)||hrRegex.test(nextLine))break;if(nextLineWithoutTabs.search(this.rules.other.nonSpaceChar)>=indent||!nextLine.trim())itemContents+=`
29
- `+nextLineWithoutTabs.slice(indent);else{if(blankLine||line.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||fencesBeginRegex.test(line)||headingBeginRegex.test(line)||hrRegex.test(line))break;itemContents+=`
30
- `+nextLine}!blankLine&&!nextLine.trim()&&(blankLine=!0),raw+=rawLine+`
31
- `,src=src.substring(rawLine.length+1),line=nextLineWithoutTabs.slice(indent)}}list2.loose||(endsWithBlankLine?list2.loose=!0:this.rules.other.doubleBlankLine.test(raw)&&(endsWithBlankLine=!0));let istask=null,ischecked;this.options.gfm&&(istask=this.rules.other.listIsTask.exec(itemContents),istask&&(ischecked=istask[0]!=="[ ] ",itemContents=itemContents.replace(this.rules.other.listReplaceTask,""))),list2.items.push({type:"list_item",raw,task:!!istask,checked:ischecked,loose:!1,text:itemContents,tokens:[]}),list2.raw+=raw}let lastItem=list2.items.at(-1);if(lastItem)lastItem.raw=lastItem.raw.trimEnd(),lastItem.text=lastItem.text.trimEnd();else return;list2.raw=list2.raw.trimEnd();for(let i=0;i<list2.items.length;i++)if(this.lexer.state.top=!1,list2.items[i].tokens=this.lexer.blockTokens(list2.items[i].text,[]),!list2.loose){let spacers=list2.items[i].tokens.filter(t=>t.type==="space"),hasMultipleLineBreaks=spacers.length>0&&spacers.some(t=>this.rules.other.anyLine.test(t.raw));list2.loose=hasMultipleLineBreaks}if(list2.loose)for(let i=0;i<list2.items.length;i++)list2.items[i].loose=!0;return list2}}html(src){let cap=this.rules.block.html.exec(src);if(cap)return{type:"html",block:!0,raw:cap[0],pre:cap[1]==="pre"||cap[1]==="script"||cap[1]==="style",text:cap[0]}}def(src){let cap=this.rules.block.def.exec(src);if(cap){let tag2=cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),href=cap[2]?cap[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",title=cap[3]?cap[3].substring(1,cap[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):cap[3];return{type:"def",tag:tag2,raw:cap[0],href,title}}}table(src){let cap=this.rules.block.table.exec(src);if(!cap||!this.rules.other.tableDelimiter.test(cap[2]))return;let headers=splitCells(cap[1]),aligns=cap[2].replace(this.rules.other.tableAlignChars,"").split("|"),rows=cap[3]?.trim()?cap[3].replace(this.rules.other.tableRowBlankLine,"").split(`
32
- `):[],item={type:"table",raw:cap[0],header:[],align:[],rows:[]};if(headers.length===aligns.length){for(let align of aligns)this.rules.other.tableAlignRight.test(align)?item.align.push("right"):this.rules.other.tableAlignCenter.test(align)?item.align.push("center"):this.rules.other.tableAlignLeft.test(align)?item.align.push("left"):item.align.push(null);for(let i=0;i<headers.length;i++)item.header.push({text:headers[i],tokens:this.lexer.inline(headers[i]),header:!0,align:item.align[i]});for(let row of rows)item.rows.push(splitCells(row,item.header.length).map((cell,i)=>({text:cell,tokens:this.lexer.inline(cell),header:!1,align:item.align[i]})));return item}}lheading(src){let cap=this.rules.block.lheading.exec(src);if(cap)return{type:"heading",raw:cap[0],depth:cap[2].charAt(0)==="="?1:2,text:cap[1],tokens:this.lexer.inline(cap[1])}}paragraph(src){let cap=this.rules.block.paragraph.exec(src);if(cap){let text=cap[1].charAt(cap[1].length-1)===`
33
- `?cap[1].slice(0,-1):cap[1];return{type:"paragraph",raw:cap[0],text,tokens:this.lexer.inline(text)}}}text(src){let cap=this.rules.block.text.exec(src);if(cap)return{type:"text",raw:cap[0],text:cap[0],tokens:this.lexer.inline(cap[0])}}escape(src){let cap=this.rules.inline.escape.exec(src);if(cap)return{type:"escape",raw:cap[0],text:cap[1]}}tag(src){let cap=this.rules.inline.tag.exec(src);if(cap)return!this.lexer.state.inLink&&this.rules.other.startATag.test(cap[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(cap[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(cap[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(cap[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:cap[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:cap[0]}}link(src){let cap=this.rules.inline.link.exec(src);if(cap){let trimmedUrl=cap[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(trimmedUrl)){if(!this.rules.other.endAngleBracket.test(trimmedUrl))return;let rtrimSlash=rtrim(trimmedUrl.slice(0,-1),"\\");if((trimmedUrl.length-rtrimSlash.length)%2===0)return}else{let lastParenIndex=findClosingBracket(cap[2],"()");if(lastParenIndex===-2)return;if(lastParenIndex>-1){let linkLen=(cap[0].indexOf("!")===0?5:4)+cap[1].length+lastParenIndex;cap[2]=cap[2].substring(0,lastParenIndex),cap[0]=cap[0].substring(0,linkLen).trim(),cap[3]=""}}let href=cap[2],title="";if(this.options.pedantic){let link2=this.rules.other.pedanticHrefTitle.exec(href);link2&&(href=link2[1],title=link2[3])}else title=cap[3]?cap[3].slice(1,-1):"";return href=href.trim(),this.rules.other.startAngleBracket.test(href)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(trimmedUrl)?href=href.slice(1):href=href.slice(1,-1)),outputLink(cap,{href:href&&href.replace(this.rules.inline.anyPunctuation,"$1"),title:title&&title.replace(this.rules.inline.anyPunctuation,"$1")},cap[0],this.lexer,this.rules)}}reflink(src,links){let cap;if((cap=this.rules.inline.reflink.exec(src))||(cap=this.rules.inline.nolink.exec(src))){let linkString=(cap[2]||cap[1]).replace(this.rules.other.multipleSpaceGlobal," "),link2=links[linkString.toLowerCase()];if(!link2){let text=cap[0].charAt(0);return{type:"text",raw:text,text}}return outputLink(cap,link2,cap[0],this.lexer,this.rules)}}emStrong(src,maskedSrc,prevChar=""){let match=this.rules.inline.emStrongLDelim.exec(src);if(!match||match[3]&&prevChar.match(this.rules.other.unicodeAlphaNumeric))return;if(!(match[1]||match[2]||"")||!prevChar||this.rules.inline.punctuation.exec(prevChar)){let lLength=[...match[0]].length-1,rDelim,rLength,delimTotal=lLength,midDelimTotal=0,endReg=match[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(endReg.lastIndex=0,maskedSrc=maskedSrc.slice(-1*src.length+lLength);(match=endReg.exec(maskedSrc))!=null;){if(rDelim=match[1]||match[2]||match[3]||match[4]||match[5]||match[6],!rDelim)continue;if(rLength=[...rDelim].length,match[3]||match[4]){delimTotal+=rLength;continue}else if((match[5]||match[6])&&lLength%3&&!((lLength+rLength)%3)){midDelimTotal+=rLength;continue}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal+midDelimTotal);let lastCharLength=[...match[0]][0].length,raw=src.slice(0,lLength+match.index+lastCharLength+rLength);if(Math.min(lLength,rLength)%2){let text2=raw.slice(1,-1);return{type:"em",raw,text:text2,tokens:this.lexer.inlineTokens(text2)}}let text=raw.slice(2,-2);return{type:"strong",raw,text,tokens:this.lexer.inlineTokens(text)}}}}codespan(src){let cap=this.rules.inline.code.exec(src);if(cap){let text=cap[2].replace(this.rules.other.newLineCharGlobal," "),hasNonSpaceChars=this.rules.other.nonSpaceChar.test(text),hasSpaceCharsOnBothEnds=this.rules.other.startingSpaceChar.test(text)&&this.rules.other.endingSpaceChar.test(text);return hasNonSpaceChars&&hasSpaceCharsOnBothEnds&&(text=text.substring(1,text.length-1)),{type:"codespan",raw:cap[0],text}}}br(src){let cap=this.rules.inline.br.exec(src);if(cap)return{type:"br",raw:cap[0]}}del(src){let cap=this.rules.inline.del.exec(src);if(cap)return{type:"del",raw:cap[0],text:cap[2],tokens:this.lexer.inlineTokens(cap[2])}}autolink(src){let cap=this.rules.inline.autolink.exec(src);if(cap){let text,href;return cap[2]==="@"?(text=cap[1],href="mailto:"+text):(text=cap[1],href=text),{type:"link",raw:cap[0],text,href,tokens:[{type:"text",raw:text,text}]}}}url(src){let cap;if(cap=this.rules.inline.url.exec(src)){let text,href;if(cap[2]==="@")text=cap[0],href="mailto:"+text;else{let prevCapZero;do prevCapZero=cap[0],cap[0]=this.rules.inline._backpedal.exec(cap[0])?.[0]??"";while(prevCapZero!==cap[0]);text=cap[0],cap[1]==="www."?href="http://"+cap[0]:href=cap[0]}return{type:"link",raw:cap[0],text,href,tokens:[{type:"text",raw:text,text}]}}}inlineText(src){let cap=this.rules.inline.text.exec(src);if(cap){let escaped=this.lexer.state.inRawBlock;return{type:"text",raw:cap[0],text:cap[0],escaped}}}},_Lexer=class __Lexer{tokens;options;state;tokenizer;inlineQueue;constructor(options2){this.tokens=[],this.tokens.links=Object.create(null),this.options=options2||_defaults,this.options.tokenizer=this.options.tokenizer||new _Tokenizer,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let rules={other,block:block.normal,inline:inline.normal};this.options.pedantic?(rules.block=block.pedantic,rules.inline=inline.pedantic):this.options.gfm&&(rules.block=block.gfm,this.options.breaks?rules.inline=inline.breaks:rules.inline=inline.gfm),this.tokenizer.rules=rules}static get rules(){return{block,inline}}static lex(src,options2){return new __Lexer(options2).lex(src)}static lexInline(src,options2){return new __Lexer(options2).inlineTokens(src)}lex(src){src=src.replace(other.carriageReturn,`
34
- `),this.blockTokens(src,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let next=this.inlineQueue[i];this.inlineTokens(next.src,next.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(src,tokens=[],lastParagraphClipped=!1){for(this.options.pedantic&&(src=src.replace(other.tabCharGlobal," ").replace(other.spaceLine,""));src;){let token;if(this.options.extensions?.block?.some(extTokenizer=>(token=extTokenizer.call({lexer:this},src,tokens))?(src=src.substring(token.raw.length),tokens.push(token),!0):!1))continue;if(token=this.tokenizer.space(src)){src=src.substring(token.raw.length);let lastToken=tokens.at(-1);token.raw.length===1&&lastToken!==void 0?lastToken.raw+=`
35
- `:tokens.push(token);continue}if(token=this.tokenizer.code(src)){src=src.substring(token.raw.length);let lastToken=tokens.at(-1);lastToken?.type==="paragraph"||lastToken?.type==="text"?(lastToken.raw+=`
36
- `+token.raw,lastToken.text+=`
37
- `+token.text,this.inlineQueue.at(-1).src=lastToken.text):tokens.push(token);continue}if(token=this.tokenizer.fences(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.heading(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.hr(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.blockquote(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.list(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.html(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.def(src)){src=src.substring(token.raw.length);let lastToken=tokens.at(-1);lastToken?.type==="paragraph"||lastToken?.type==="text"?(lastToken.raw+=`
38
- `+token.raw,lastToken.text+=`
39
- `+token.raw,this.inlineQueue.at(-1).src=lastToken.text):this.tokens.links[token.tag]||(this.tokens.links[token.tag]={href:token.href,title:token.title});continue}if(token=this.tokenizer.table(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.lheading(src)){src=src.substring(token.raw.length),tokens.push(token);continue}let cutSrc=src;if(this.options.extensions?.startBlock){let startIndex=1/0,tempSrc=src.slice(1),tempStart;this.options.extensions.startBlock.forEach(getStartIndex=>{tempStart=getStartIndex.call({lexer:this},tempSrc),typeof tempStart=="number"&&tempStart>=0&&(startIndex=Math.min(startIndex,tempStart))}),startIndex<1/0&&startIndex>=0&&(cutSrc=src.substring(0,startIndex+1))}if(this.state.top&&(token=this.tokenizer.paragraph(cutSrc))){let lastToken=tokens.at(-1);lastParagraphClipped&&lastToken?.type==="paragraph"?(lastToken.raw+=`
40
- `+token.raw,lastToken.text+=`
41
- `+token.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=lastToken.text):tokens.push(token),lastParagraphClipped=cutSrc.length!==src.length,src=src.substring(token.raw.length);continue}if(token=this.tokenizer.text(src)){src=src.substring(token.raw.length);let lastToken=tokens.at(-1);lastToken?.type==="text"?(lastToken.raw+=`
42
- `+token.raw,lastToken.text+=`
43
- `+token.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=lastToken.text):tokens.push(token);continue}if(src){let errMsg="Infinite loop on byte: "+src.charCodeAt(0);if(this.options.silent){console.error(errMsg);break}else throw new Error(errMsg)}}return this.state.top=!0,tokens}inline(src,tokens=[]){return this.inlineQueue.push({src,tokens}),tokens}inlineTokens(src,tokens=[]){let maskedSrc=src,match=null;if(this.tokens.links){let links=Object.keys(this.tokens.links);if(links.length>0)for(;(match=this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc))!=null;)links.includes(match[0].slice(match[0].lastIndexOf("[")+1,-1))&&(maskedSrc=maskedSrc.slice(0,match.index)+"["+"a".repeat(match[0].length-2)+"]"+maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(match=this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc))!=null;)maskedSrc=maskedSrc.slice(0,match.index)+"++"+maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(match=this.tokenizer.rules.inline.blockSkip.exec(maskedSrc))!=null;)maskedSrc=maskedSrc.slice(0,match.index)+"["+"a".repeat(match[0].length-2)+"]"+maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let keepPrevChar=!1,prevChar="";for(;src;){keepPrevChar||(prevChar=""),keepPrevChar=!1;let token;if(this.options.extensions?.inline?.some(extTokenizer=>(token=extTokenizer.call({lexer:this},src,tokens))?(src=src.substring(token.raw.length),tokens.push(token),!0):!1))continue;if(token=this.tokenizer.escape(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.tag(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.link(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.reflink(src,this.tokens.links)){src=src.substring(token.raw.length);let lastToken=tokens.at(-1);token.type==="text"&&lastToken?.type==="text"?(lastToken.raw+=token.raw,lastToken.text+=token.text):tokens.push(token);continue}if(token=this.tokenizer.emStrong(src,maskedSrc,prevChar)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.codespan(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.br(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.del(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(token=this.tokenizer.autolink(src)){src=src.substring(token.raw.length),tokens.push(token);continue}if(!this.state.inLink&&(token=this.tokenizer.url(src))){src=src.substring(token.raw.length),tokens.push(token);continue}let cutSrc=src;if(this.options.extensions?.startInline){let startIndex=1/0,tempSrc=src.slice(1),tempStart;this.options.extensions.startInline.forEach(getStartIndex=>{tempStart=getStartIndex.call({lexer:this},tempSrc),typeof tempStart=="number"&&tempStart>=0&&(startIndex=Math.min(startIndex,tempStart))}),startIndex<1/0&&startIndex>=0&&(cutSrc=src.substring(0,startIndex+1))}if(token=this.tokenizer.inlineText(cutSrc)){src=src.substring(token.raw.length),token.raw.slice(-1)!=="_"&&(prevChar=token.raw.slice(-1)),keepPrevChar=!0;let lastToken=tokens.at(-1);lastToken?.type==="text"?(lastToken.raw+=token.raw,lastToken.text+=token.text):tokens.push(token);continue}if(src){let errMsg="Infinite loop on byte: "+src.charCodeAt(0);if(this.options.silent){console.error(errMsg);break}else throw new Error(errMsg)}}return tokens}},_Renderer=class{options;parser;constructor(options2){this.options=options2||_defaults}space(token){return""}code({text,lang,escaped}){let langString=(lang||"").match(other.notSpaceStart)?.[0],code=text.replace(other.endingNewline,"")+`
44
- `;return langString?'<pre><code class="language-'+escape2(langString)+'">'+(escaped?code:escape2(code,!0))+`</code></pre>
45
- `:"<pre><code>"+(escaped?code:escape2(code,!0))+`</code></pre>
46
- `}blockquote({tokens}){return`<blockquote>
47
- ${this.parser.parse(tokens)}</blockquote>
48
- `}html({text}){return text}heading({tokens,depth}){return`<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
49
- `}hr(token){return`<hr>
50
- `}list(token){let ordered=token.ordered,start=token.start,body="";for(let j=0;j<token.items.length;j++){let item=token.items[j];body+=this.listitem(item)}let type=ordered?"ol":"ul",startAttr=ordered&&start!==1?' start="'+start+'"':"";return"<"+type+startAttr+`>
51
- `+body+"</"+type+`>
52
- `}listitem(item){let itemBody="";if(item.task){let checkbox=this.checkbox({checked:!!item.checked});item.loose?item.tokens[0]?.type==="paragraph"?(item.tokens[0].text=checkbox+" "+item.tokens[0].text,item.tokens[0].tokens&&item.tokens[0].tokens.length>0&&item.tokens[0].tokens[0].type==="text"&&(item.tokens[0].tokens[0].text=checkbox+" "+escape2(item.tokens[0].tokens[0].text),item.tokens[0].tokens[0].escaped=!0)):item.tokens.unshift({type:"text",raw:checkbox+" ",text:checkbox+" ",escaped:!0}):itemBody+=checkbox+" "}return itemBody+=this.parser.parse(item.tokens,!!item.loose),`<li>${itemBody}</li>
53
- `}checkbox({checked}){return"<input "+(checked?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens}){return`<p>${this.parser.parseInline(tokens)}</p>
54
- `}table(token){let header="",cell="";for(let j=0;j<token.header.length;j++)cell+=this.tablecell(token.header[j]);header+=this.tablerow({text:cell});let body="";for(let j=0;j<token.rows.length;j++){let row=token.rows[j];cell="";for(let k=0;k<row.length;k++)cell+=this.tablecell(row[k]);body+=this.tablerow({text:cell})}return body&&(body=`<tbody>${body}</tbody>`),`<table>
55
- <thead>
56
- `+header+`</thead>
57
- `+body+`</table>
58
- `}tablerow({text}){return`<tr>
59
- ${text}</tr>
60
- `}tablecell(token){let content=this.parser.parseInline(token.tokens),type=token.header?"th":"td";return(token.align?`<${type} align="${token.align}">`:`<${type}>`)+content+`</${type}>
61
- `}strong({tokens}){return`<strong>${this.parser.parseInline(tokens)}</strong>`}em({tokens}){return`<em>${this.parser.parseInline(tokens)}</em>`}codespan({text}){return`<code>${escape2(text,!0)}</code>`}br(token){return"<br>"}del({tokens}){return`<del>${this.parser.parseInline(tokens)}</del>`}link({href,title,tokens}){let text=this.parser.parseInline(tokens),cleanHref=cleanUrl(href);if(cleanHref===null)return text;href=cleanHref;let out='<a href="'+href+'"';return title&&(out+=' title="'+escape2(title)+'"'),out+=">"+text+"</a>",out}image({href,title,text,tokens}){tokens&&(text=this.parser.parseInline(tokens,this.parser.textRenderer));let cleanHref=cleanUrl(href);if(cleanHref===null)return escape2(text);href=cleanHref;let out=`<img src="${href}" alt="${text}"`;return title&&(out+=` title="${escape2(title)}"`),out+=">",out}text(token){return"tokens"in token&&token.tokens?this.parser.parseInline(token.tokens):"escaped"in token&&token.escaped?token.text:escape2(token.text)}},_TextRenderer=class{strong({text}){return text}em({text}){return text}codespan({text}){return text}del({text}){return text}html({text}){return text}text({text}){return text}link({text}){return""+text}image({text}){return""+text}br(){return""}},_Parser=class __Parser{options;renderer;textRenderer;constructor(options2){this.options=options2||_defaults,this.options.renderer=this.options.renderer||new _Renderer,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _TextRenderer}static parse(tokens,options2){return new __Parser(options2).parse(tokens)}static parseInline(tokens,options2){return new __Parser(options2).parseInline(tokens)}parse(tokens,top=!0){let out="";for(let i=0;i<tokens.length;i++){let anyToken=tokens[i];if(this.options.extensions?.renderers?.[anyToken.type]){let genericToken=anyToken,ret=this.options.extensions.renderers[genericToken.type].call({parser:this},genericToken);if(ret!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(genericToken.type)){out+=ret||"";continue}}let token=anyToken;switch(token.type){case"space":{out+=this.renderer.space(token);continue}case"hr":{out+=this.renderer.hr(token);continue}case"heading":{out+=this.renderer.heading(token);continue}case"code":{out+=this.renderer.code(token);continue}case"table":{out+=this.renderer.table(token);continue}case"blockquote":{out+=this.renderer.blockquote(token);continue}case"list":{out+=this.renderer.list(token);continue}case"html":{out+=this.renderer.html(token);continue}case"paragraph":{out+=this.renderer.paragraph(token);continue}case"text":{let textToken=token,body=this.renderer.text(textToken);for(;i+1<tokens.length&&tokens[i+1].type==="text";)textToken=tokens[++i],body+=`
62
- `+this.renderer.text(textToken);top?out+=this.renderer.paragraph({type:"paragraph",raw:body,text:body,tokens:[{type:"text",raw:body,text:body,escaped:!0}]}):out+=body;continue}default:{let errMsg='Token with "'+token.type+'" type was not found.';if(this.options.silent)return console.error(errMsg),"";throw new Error(errMsg)}}}return out}parseInline(tokens,renderer=this.renderer){let out="";for(let i=0;i<tokens.length;i++){let anyToken=tokens[i];if(this.options.extensions?.renderers?.[anyToken.type]){let ret=this.options.extensions.renderers[anyToken.type].call({parser:this},anyToken);if(ret!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(anyToken.type)){out+=ret||"";continue}}let token=anyToken;switch(token.type){case"escape":{out+=renderer.text(token);break}case"html":{out+=renderer.html(token);break}case"link":{out+=renderer.link(token);break}case"image":{out+=renderer.image(token);break}case"strong":{out+=renderer.strong(token);break}case"em":{out+=renderer.em(token);break}case"codespan":{out+=renderer.codespan(token);break}case"br":{out+=renderer.br(token);break}case"del":{out+=renderer.del(token);break}case"text":{out+=renderer.text(token);break}default:{let errMsg='Token with "'+token.type+'" type was not found.';if(this.options.silent)return console.error(errMsg),"";throw new Error(errMsg)}}}return out}},_Hooks=class{options;block;constructor(options2){this.options=options2||_defaults}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(markdown){return markdown}postprocess(html2){return html2}processAllTokens(tokens){return tokens}provideLexer(){return this.block?_Lexer.lex:_Lexer.lexInline}provideParser(){return this.block?_Parser.parse:_Parser.parseInline}},Marked=class{defaults=_getDefaults();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=_Parser;Renderer=_Renderer;TextRenderer=_TextRenderer;Lexer=_Lexer;Tokenizer=_Tokenizer;Hooks=_Hooks;constructor(...args){this.use(...args)}walkTokens(tokens,callback){let values=[];for(let token of tokens)switch(values=values.concat(callback.call(this,token)),token.type){case"table":{let tableToken=token;for(let cell of tableToken.header)values=values.concat(this.walkTokens(cell.tokens,callback));for(let row of tableToken.rows)for(let cell of row)values=values.concat(this.walkTokens(cell.tokens,callback));break}case"list":{let listToken=token;values=values.concat(this.walkTokens(listToken.items,callback));break}default:{let genericToken=token;this.defaults.extensions?.childTokens?.[genericToken.type]?this.defaults.extensions.childTokens[genericToken.type].forEach(childTokens=>{let tokens2=genericToken[childTokens].flat(1/0);values=values.concat(this.walkTokens(tokens2,callback))}):genericToken.tokens&&(values=values.concat(this.walkTokens(genericToken.tokens,callback)))}}return values}use(...args){let extensions=this.defaults.extensions||{renderers:{},childTokens:{}};return args.forEach(pack=>{let opts={...pack};if(opts.async=this.defaults.async||opts.async||!1,pack.extensions&&(pack.extensions.forEach(ext=>{if(!ext.name)throw new Error("extension name required");if("renderer"in ext){let prevRenderer=extensions.renderers[ext.name];prevRenderer?extensions.renderers[ext.name]=function(...args2){let ret=ext.renderer.apply(this,args2);return ret===!1&&(ret=prevRenderer.apply(this,args2)),ret}:extensions.renderers[ext.name]=ext.renderer}if("tokenizer"in ext){if(!ext.level||ext.level!=="block"&&ext.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let extLevel=extensions[ext.level];extLevel?extLevel.unshift(ext.tokenizer):extensions[ext.level]=[ext.tokenizer],ext.start&&(ext.level==="block"?extensions.startBlock?extensions.startBlock.push(ext.start):extensions.startBlock=[ext.start]:ext.level==="inline"&&(extensions.startInline?extensions.startInline.push(ext.start):extensions.startInline=[ext.start]))}"childTokens"in ext&&ext.childTokens&&(extensions.childTokens[ext.name]=ext.childTokens)}),opts.extensions=extensions),pack.renderer){let renderer=this.defaults.renderer||new _Renderer(this.defaults);for(let prop in pack.renderer){if(!(prop in renderer))throw new Error(`renderer '${prop}' does not exist`);if(["options","parser"].includes(prop))continue;let rendererProp=prop,rendererFunc=pack.renderer[rendererProp],prevRenderer=renderer[rendererProp];renderer[rendererProp]=(...args2)=>{let ret=rendererFunc.apply(renderer,args2);return ret===!1&&(ret=prevRenderer.apply(renderer,args2)),ret||""}}opts.renderer=renderer}if(pack.tokenizer){let tokenizer=this.defaults.tokenizer||new _Tokenizer(this.defaults);for(let prop in pack.tokenizer){if(!(prop in tokenizer))throw new Error(`tokenizer '${prop}' does not exist`);if(["options","rules","lexer"].includes(prop))continue;let tokenizerProp=prop,tokenizerFunc=pack.tokenizer[tokenizerProp],prevTokenizer=tokenizer[tokenizerProp];tokenizer[tokenizerProp]=(...args2)=>{let ret=tokenizerFunc.apply(tokenizer,args2);return ret===!1&&(ret=prevTokenizer.apply(tokenizer,args2)),ret}}opts.tokenizer=tokenizer}if(pack.hooks){let hooks=this.defaults.hooks||new _Hooks;for(let prop in pack.hooks){if(!(prop in hooks))throw new Error(`hook '${prop}' does not exist`);if(["options","block"].includes(prop))continue;let hooksProp=prop,hooksFunc=pack.hooks[hooksProp],prevHook=hooks[hooksProp];_Hooks.passThroughHooks.has(prop)?hooks[hooksProp]=arg=>{if(this.defaults.async)return Promise.resolve(hooksFunc.call(hooks,arg)).then(ret2=>prevHook.call(hooks,ret2));let ret=hooksFunc.call(hooks,arg);return prevHook.call(hooks,ret)}:hooks[hooksProp]=(...args2)=>{let ret=hooksFunc.apply(hooks,args2);return ret===!1&&(ret=prevHook.apply(hooks,args2)),ret}}opts.hooks=hooks}if(pack.walkTokens){let walkTokens2=this.defaults.walkTokens,packWalktokens=pack.walkTokens;opts.walkTokens=function(token){let values=[];return values.push(packWalktokens.call(this,token)),walkTokens2&&(values=values.concat(walkTokens2.call(this,token))),values}}this.defaults={...this.defaults,...opts}}),this}setOptions(opt){return this.defaults={...this.defaults,...opt},this}lexer(src,options2){return _Lexer.lex(src,options2??this.defaults)}parser(tokens,options2){return _Parser.parse(tokens,options2??this.defaults)}parseMarkdown(blockType){return(src,options2)=>{let origOpt={...options2},opt={...this.defaults,...origOpt},throwError=this.onError(!!opt.silent,!!opt.async);if(this.defaults.async===!0&&origOpt.async===!1)return throwError(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 src>"u"||src===null)return throwError(new Error("marked(): input parameter is undefined or null"));if(typeof src!="string")return throwError(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(src)+", string expected"));opt.hooks&&(opt.hooks.options=opt,opt.hooks.block=blockType);let lexer2=opt.hooks?opt.hooks.provideLexer():blockType?_Lexer.lex:_Lexer.lexInline,parser2=opt.hooks?opt.hooks.provideParser():blockType?_Parser.parse:_Parser.parseInline;if(opt.async)return Promise.resolve(opt.hooks?opt.hooks.preprocess(src):src).then(src2=>lexer2(src2,opt)).then(tokens=>opt.hooks?opt.hooks.processAllTokens(tokens):tokens).then(tokens=>opt.walkTokens?Promise.all(this.walkTokens(tokens,opt.walkTokens)).then(()=>tokens):tokens).then(tokens=>parser2(tokens,opt)).then(html2=>opt.hooks?opt.hooks.postprocess(html2):html2).catch(throwError);try{opt.hooks&&(src=opt.hooks.preprocess(src));let tokens=lexer2(src,opt);opt.hooks&&(tokens=opt.hooks.processAllTokens(tokens)),opt.walkTokens&&this.walkTokens(tokens,opt.walkTokens);let html2=parser2(tokens,opt);return opt.hooks&&(html2=opt.hooks.postprocess(html2)),html2}catch(e){return throwError(e)}}}onError(silent,async){return e=>{if(e.message+=`
63
- Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>An error occurred:</p><pre>"+escape2(e.message+"",!0)+"</pre>";return async?Promise.resolve(msg):msg}if(async)return Promise.reject(e);throw e}}},markedInstance=new Marked;function marked(src,opt){return markedInstance.parse(src,opt)}marked.options=marked.setOptions=function(options2){return markedInstance.setOptions(options2),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked};marked.getDefaults=_getDefaults;marked.defaults=_defaults;marked.use=function(...args){return markedInstance.use(...args),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked};marked.walkTokens=function(tokens,callback){return markedInstance.walkTokens(tokens,callback)};marked.parseInline=markedInstance.parseInline;marked.Parser=_Parser;marked.parser=_Parser.parse;marked.Renderer=_Renderer;marked.TextRenderer=_TextRenderer;marked.Lexer=_Lexer;marked.lexer=_Lexer.lex;marked.Tokenizer=_Tokenizer;marked.Hooks=_Hooks;marked.parse=marked;var options=marked.options,setOptions=marked.setOptions,use=marked.use,walkTokens=marked.walkTokens,parseInline=marked.parseInline;var parser=_Parser.parse,lexer=_Lexer.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]);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]+)$/),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.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 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,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,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,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,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;for(;low<=high;){let mid=Math.floor((low+high)/2),i=mid*2;if(codePoint<ranges[i])high=mid-1;else if(codePoint>ranges[i+1])low=mid+1;else return!0}return!1};var commonCjkCodePoint=19968,[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges);function findWideFastPathRange(ranges){let fastPathStart=ranges[0],fastPathEnd=ranges[1];for(let index=0;index<ranges.length;index+=2){let start=ranges[index],end=ranges[index+1];if(commonCjkCodePoint>=start&&commonCjkCodePoint<=end)return[start,end];end-start>fastPathEnd-fastPathStart&&(fastPathStart=start,fastPathEnd=end)}return[fastPathStart,fastPathEnd]}var isAmbiguous=codePoint=>codePoint<161||codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullWidth=codePoint=>codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint?!1:isInRange(fullwidthRanges,codePoint);var isWide=codePoint=>codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd?!0:codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint?!1:isInRange(wideRanges,codePoint);function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){return validate(codePoint),isFullWidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint)?2:1}var graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"}),wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"});function getGraphemeSegmenter(){return graphemeSegmenter}function getWordSegmenter(){return wordSegmenter}function couldBeEmoji(segment){let cp=segment.codePointAt(0);return cp>=126976&&cp<=130047||cp>=8960&&cp<=9215||cp>=9728&&cp<=10175||cp>=11088&&cp<=11093||segment.includes("\uFE0F")||segment.length>2}var zeroWidthRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","u"),leadingNonPrintingRegex=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/u,nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","u"),markCharRegex=new RegExp("^\\p{Mark}$","u"),terminalSpacingMarkRegex=new RegExp("^(?:(?:(?!\\u1734|\\u302E|\\u302F)\\p{Spacing_Mark})|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","u"),extendedPictographicRegex=new RegExp("\\p{Extended_Pictographic}","u"),emojiJoinerRegex=new RegExp("^(?:\\p{Emoji_Modifier}|\\p{Mark}|\\u200D|\\uFE0F|\\u20E3)$","u");function isRegionalIndicator(codePoint){return codePoint>=127462&&codePoint<=127487}function isKeycapBase(char){return/^[#*0-9]$/u.test(char)}function isEmojiGrapheme(segment){let sawEmojiBase=!1;for(let char of segment){let codePoint=char.codePointAt(0);if(codePoint!==void 0){if(extendedPictographicRegex.test(char)||isRegionalIndicator(codePoint)||isKeycapBase(char)){sawEmojiBase=!0;continue}if(!emojiJoinerRegex.test(char))return!1}}return sawEmojiBase}var 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(`(?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str2){for(let i=0;i<str2.length;i++){let code=str2.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"),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+=" ",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),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(segment)&&isEmojiGrapheme(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(c2):(c2===3635||c2===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str2){if(str2.length===0)return 0;let asciiWidth=asciiVisibleWidth(str2);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str2);if(cached!==void 0)return cached;let clean=str2;str2.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+=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(str2,width),width}function stripTerminalSequences(str2){if(!str2.includes("\x1B"))return str2;let result="",i=0;for(;i<str2.length;){let ansi=extractAnsiCode(str2,i);if(ansi){i+=ansi.length;continue}result+=str2[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&&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.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(str2){let normalized=str2;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;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(str2,pos){let length=ansiCodeLength(str2,pos);return length>0?{code:str2.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str2){let width=0,i=0;for(;i<str2.length;){let code=str2.charCodeAt(i);if(code>=32&&code<=126)width++,i++;else if(code===9)width+=3,i++;else if(code===27){let length=ansiCodeLength(str2,i);if(length===0)return-1;i+=length}else return-1}return width}function ansiCodeLength(str2,pos){if(pos>=str2.length||str2.charCodeAt(pos)!==27)return 0;let next=str2[pos+1];if(next==="["){for(let j=pos+2;j<str2.length;j++){let c2=str2.charCodeAt(j);if(c2===109||c2===71||c2===75||c2===72||c2===74)return j+1-pos}return 0}if(next==="]"||next==="_"){for(let j=pos+2;j<str2.length;j++){let c2=str2.charCodeAt(j);if(c2===7)return j+1-pos;if(c2===27&&str2[j+1]==="\\")return j+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.startsWith("\x1B]8;"))return;let terminator=ansiCode.endsWith("\x07")?"\x07":"\x1B\\",body=ansiCode.slice(4,terminator==="\x07"?-1:-2),separatorIndex=body.indexOf(";");if(separatorIndex===-1)return;let params=body.slice(0,separatorIndex),url=body.slice(separatorIndex+1);return url?{params,url,terminator}:null}function formatOsc8Hyperlink(hyperlink2){return`\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`}function formatOsc8Close(terminator){return`\x1B]8;;${terminator}`}function getActiveOsc8Close(prefix){if(!prefix.includes("\x1B]8;"))return"";let activeHyperlink=null,i=0;for(;i<prefix.length;){let ansi=extractAnsiCode(prefix,i);if(ansi){let hyperlink2=parseOsc8Hyperlink(ansi.code);hyperlink2!==void 0&&(activeHyperlink=hyperlink2),i+=ansi.length}else i++}return activeHyperlink?formatOsc8Close(activeHyperlink.terminator):""}var AnsiCodeTracker=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(ansiCode){let hyperlink2=parseOsc8Hyperlink(ansiCode);if(hyperlink2!==void 0){this.activeHyperlink=hyperlink2;return}if(!ansiCode.endsWith("m"))return;let match=ansiCode.match(/\x1b\[([\d;]*)m/);if(!match)return;let params=match[1];if(params===""||params==="0"){this.reset();return}let parts=params.split(";"),i=0;for(;i<parts.length;){let code=Number.parseInt(parts[i],10);if(code===38||code===48){if(parts[i+1]==="5"&&parts[i+2]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=3;continue}else if(parts[i+1]==="2"&&parts[i+4]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]};${parts[i+3]};${parts[i+4]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=5;continue}}switch(code){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:code>=30&&code<=37||code>=90&&code<=97?this.fgColor=String(code):(code>=40&&code<=47||code>=100&&code<=107)&&(this.bgColor=String(code));break}i++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let codes=[];this.bold&&codes.push("1"),this.dim&&codes.push("2"),this.italic&&codes.push("3"),this.underline&&codes.push("4"),this.blink&&codes.push("5"),this.inverse&&codes.push("7"),this.hidden&&codes.push("8"),this.strikethrough&&codes.push("9"),this.fgColor&&codes.push(this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`\x1B[${codes.join(";")}m`:"";return this.activeHyperlink&&(result+=formatOsc8Hyperlink(this.activeHyperlink)),result}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let result="";return this.underline&&(result+="\x1B[24m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),tracker.getActiveBackgroundCode()}function*graphemeSegments(text){for(let{segment}of graphemeSegmenter.segment(text))yield segment}function splitIntoTokensWithAnsi(text){let tokens=[],current="",pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),current="",currentKind=null)};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=text.length);let chunk=text.slice(i,end),ascii=isPrintableAscii(chunk);for(let segment of ascii?chunk:graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!ascii&&!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token);continue}let segmentKind=segmentIsSpace?"space":"word";current&&currentKind!==segmentKind&&flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment}i=end}return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let inputLine of inputLines){let prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);for(let wrappedLine of wrappedLines)result.push(wrappedLine);updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}function wrapSingleLine(line,width){if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let token of tokens){let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&&currentVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0):(currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function applyBackgroundToLine(line,width,bgFn){let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding;return bgFn(withPadding)}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of graphemeSegmenter.segment(text)){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(result+=segment,keptWidth+=width):keepContiguousPrefix=!1,visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}exhaustedInput=!overflowed}else{let i=0;for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){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&&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){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(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){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(line,textEnd);)textEnd++;for(let{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)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}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 escapeRegex(normalized);let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",pattern=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment)).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))&&(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-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.startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path5,options2){let needsQuotes=options2.isQuotedPrefix||autocompleteSeparatorRegex.test(path5),prefix=options2.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path5}"`:`${prefix}${path5}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,finish=results=>{resolved||(resolved=!0,signal.removeEventListener("abort",onAbort),resolve(results))},onAbort=()=>{child.exitCode===null&&child.kill("SIGKILL")};signal.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk}),child.on("error",()=>{finish([])}),child.on("close",code=>{if(signal.aborted||code!==0||!stdout){finish([]);return}let lines=stdout.trim().split(`
64
- `).filter(Boolean),results=[];for(let line of lines){let displayLine=toDisplayPath(line),hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")||results.push({path:displayLine,isDirectory:hasTrailingSeparator})}finish(results)})})}var CombinedAutocompleteProvider=class{commands;basePath;fdPath;constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}async getSuggestions(lines,cursorLine,cursorCol,options2){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options2.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.trimStart();if(!options2.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");if(spaceIndex===-1){let prefix=commandText.slice(1),commandItems=this.commands.map(cmd=>{let name="name"in cmd?cmd.name:cmd.value,hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} \u2014 ${desc}`:hint:desc;return{name,label:name,description:fullDesc||void 0}}),bareNameMatches=fuzzyFilter(commandItems,prefix,item=>item.name.startsWith("skill:")?item.name.slice(6):item.name),bareNameMatchSet=new Set(bareNameMatches),fullNameOnlyMatches=fuzzyFilter(commandItems.filter(item=>item.name.startsWith("skill:")&&!bareNameMatchSet.has(item)),prefix,item=>item.name),filtered=[...bareNameMatches,...fullNameOnlyMatches].map(item=>({value:item.name,label:item.label,...item.description&&{description:item.description}}));return filtered.length===0?null:{items:filtered,prefix:commandText}}let commandName=commandText.slice(1,spaceIndex),argumentText=commandText.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName);if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options2.force??!1);if(pathMatch===null)return null;let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.startsWith("/")&&beforePrefix.trim()===""&&!prefix.slice(1).includes("/")){let newLine2=`${beforePrefix}/${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+2}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+cursorOffset}}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path5){if(path5.startsWith("~/")){let expandedPath=join(homedir(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir();return path5}resolveScopedFuzzyQuery(rawQuery){let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join(this.basePath,displayBase);try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=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(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{}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(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("/"),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){return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options2){if(!this.fdPath||options2.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options2.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options2.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(options2.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("/").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,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options2.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.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};var multiply=(m,[x,y,z])=>m.map(row=>row[0]*x+row[1]*y+row[2]*z),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,-.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,.00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x=>.5*(K3*x-K1+Math.sqrt((K3*x-K1)**2+4*K2*K3*x)),okhslToOklabLightness=x=>(x*x+K1*x)/(K3*(x+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(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(([[x,y]],index)=>index===2||x*a+y*b>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],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(k=>1+saturation*k),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([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(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(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(L,a,b){let peak=cusp(a,b),cMax=maxChroma(a,b,L,peak),k=cMax/Math.min(L*(peak[1]/peak[0]),(1-L)*(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*b+a*(-.27087943+.6122399*b+a*(.00299215-.45399568*b-.14661872*a)))),cMid=.9*k*Math.sqrt(Math.sqrt(1/(1/(L*midS)**4+1/((1-L)*midT)**4)));return[Math.sqrt(1/(1/(L*.4)**2+1/((1-L)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L=okhslToOklabLightness(lightness),lab=[L,0,0];if(L>0&&L<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(L,a,b),chroma;if(saturation<.8){let t=1.25*saturation,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=[L,chroma*a,chroma*b]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L);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(L,labA/chroma,labB/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.freeze({kind:"rgb",r,g,b})}function oklchColor(l,c2,h){if(requireFinite(l,"l"),requireFinite(c2,"c"),requireFinite(h,"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:(h%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*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h,s,l){if(requireFinite(h,"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(h,s,l);return rgbColor(r,g,b)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){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(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,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},(_,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.every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l,c:c2,h}){let radians=h*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(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,a,b]=rgbToOklab(colorToRgb(color));return{l,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(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)%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){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})<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,!0)}function styleText(text,options2,mode){return styleTextWithAnsi(text,options2.fg&&foregroundAnsi(options2.fg,mode),options2.bg&&backgroundAnsi(options2.bg,mode),options2)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options2){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options2.bold&&(prefix+="\x1B[1m"),options2.dim&&(prefix+="\x1B[2m"),(options2.bold||options2.dim)&&(suffix=`\x1B[22m${suffix}`),options2.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options2.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options2.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options2.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}import{performance as performance2}from"node:perf_hooks";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",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}`,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(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),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([[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.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);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~","\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:["\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+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":"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===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(":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],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={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.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){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(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&&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){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.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){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){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}function parseKeyId(keyId){let key=keyId.toLowerCase(),modifiers=new Set;for(;;){let modifier=MODIFIER_NAMES.find(name=>key.startsWith(`${name}+`));if(!modifier)break;if(modifiers.has(modifier))return null;modifiers.add(modifier),key=key.slice(modifier.length+1)}return!key||key.includes("+")&&key!=="+"?null:{key,ctrl:modifiers.has("ctrl"),shift:modifiers.has("shift"),alt:modifiers.has("alt"),super:modifiers.has("super")}}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&&(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(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?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
65
- `:!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===`
66
- `||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===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(data,LEGACY_KEY_SEQUENCES.insert)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,0):matchesLegacyModifierSequence(data,"insert",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,modifier);case"delete":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.delete)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,0):matchesLegacyModifierSequence(data,"delete",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,modifier);case"clear":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.clear):matchesLegacyModifierSequence(data,"clear",modifier);case"home":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.home)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,0):matchesLegacyModifierSequence(data,"home",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,modifier);case"end":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.end)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,0):matchesLegacyModifierSequence(data,"end",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,modifier);case"pageup":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageUp)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,0):matchesLegacyModifierSequence(data,"pageUp",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,modifier);case"pagedown":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageDown)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageDown",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,modifier);case"up":return modifier===MODIFIERS.alt?data==="\x1Bp"||matchesKittySequence(data,ARROW_CODEPOINTS.up,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.up)||matchesKittySequence(data,ARROW_CODEPOINTS.up,0):matchesLegacyModifierSequence(data,"up",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.up,modifier);case"down":return modifier===MODIFIERS.alt?data==="\x1Bn"||matchesKittySequence(data,ARROW_CODEPOINTS.down,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.down)||matchesKittySequence(data,ARROW_CODEPOINTS.down,0):matchesLegacyModifierSequence(data,"down",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.down,modifier);case"left":return modifier===MODIFIERS.alt?data==="\x1B[1;3D"||!_kittyProtocolActive&&data==="\x1BB"||data==="\x1Bb"||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyModifierSequence(data,"left",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.left)||matchesKittySequence(data,ARROW_CODEPOINTS.left,0):matchesLegacyModifierSequence(data,"left",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.left,modifier);case"right":return modifier===MODIFIERS.alt?data==="\x1B[1;3C"||!_kittyProtocolActive&&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"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&&!_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()?!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(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.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.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(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.modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
67
- `))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===`
68
- `||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&&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"||data==="\x1BOF")return"end";if(data==="\x1B[3~")return"delete";if(data==="\x1B[5~")return"pageUp";if(data==="\x1B[6~")return"pageDown";if(data.length===1){let code=data.charCodeAt(0);if(code>=1&&code<=26)return`ctrl+${String.fromCharCode(code+96)}`;if(code>=32&&code<=126)return data}}var KITTY_CSI_U_REGEX=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KITTY_PRINTABLE_ALLOWED_MODIFIERS=MODIFIERS.shift|LOCK_MASK;function decodeKittyPrintable(data){let match=data.match(KITTY_CSI_U_REGEX);if(!match)return;let codepoint=Number.parseInt(match[1]??"",10);if(!Number.isFinite(codepoint))return;let shiftedKey=match[2]&&match[2].length>0?Number.parseInt(match[2],10):void 0,modValue=match[4]?Number.parseInt(match[4],10):1,modifier=Number.isFinite(modValue)?modValue-1:0;if((modifier&~KITTY_PRINTABLE_ALLOWED_MODIFIERS)!==0||modifier&(MODIFIERS.alt|MODIFIERS.ctrl))return;let effectiveCodepoint=codepoint;if(modifier&MODIFIERS.shift&&typeof shiftedKey=="number"&&(effectiveCodepoint=shiftedKey),effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32))try{return String.fromCodePoint(effectiveCodepoint)}catch{return}}function decodeModifyOtherKeysPrintable(data){let parsed=parseModifyOtherKeysSequence(data);if(!(!parsed||(parsed.modifier&~LOCK_MASK&~MODIFIERS.shift)!==0)&&!(!Number.isFinite(parsed.codepoint)||parsed.codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}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)+$/;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.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)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","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==="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}:termProgram==="rex"?{images:"kitty",trueColor:!0,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}: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}: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.DRAHT_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=process.env.DRAHT_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.DRAHT_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==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===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(Math.random()*4294967294)+1}function encodeKitty(base64Data,options2={}){let params=["a=T","f=100","q=2"];if(options2.moveCursor===!1&&params.push("C=1"),options2.columns&&params.push(`c=${options2.columns}`),options2.rows&&params.push(`r=${options2.rows}`),options2.imageId&&params.push(`i=${options2.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.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,options2={}){let params=[`inline=${options2.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options2.width!==void 0&&params.push(`width=${options2.width}`),options2.height!==void 0&&params.push(`height=${options2.height}`),options2.name){let nameBase64=Buffer.from(options2.name).toString("base64");params.push(`name=${nameBase64}`)}return options2.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;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];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){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===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===-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.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>=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}`,`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={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*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*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;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+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}}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<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(base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options2={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options2.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options2.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options2.imageId!==void 0&&registerKittyImageMetadata({imageId:options2.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options2.imageId,moveCursor:options2.moveCursor}),columns:size.columns,rows:size.rows,imageId:options2.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options2.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){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.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){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},(_,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_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 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){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){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,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)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@draht/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(){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){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){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?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):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options2){let entry={component,...options2===void 0?{}:{options:options2},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options2?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options2?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options2={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options2),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options2)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=performance2.now(),this.doRender()}requestRender(force=!1){if(force){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=performance2.now()-this.lastRenderAt,delay=Math.max(0,_TuiBase.MIN_RENDER_INTERVAL_MS-elapsed);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},delay)}handleTerminalInput(data){if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options2,overlayHeight,termWidth,termHeight){let opt=options2??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("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.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"bottom-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){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:options2}=entry,{width,maxHeight}=this.resolveOverlayLayout(options2,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options2,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(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){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!==-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({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;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.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;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.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))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 TUI_KEYBINDINGS={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function normalizeKeys(keys){if(keys===void 0)return[];let keyList=Array.isArray(keys)?keys:[keys],seen=new Set,result=[];for(let key of keyList)seen.has(key)||(seen.add(key),result.push(key));return result}var KeybindingsManager=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(definitions,userBindings={}){this.definitions=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.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.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(TUI_KEYBINDINGS)),globalKeybindings}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.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-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=" ".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,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.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(),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,options2){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options2?.segment,isAtomic=options2?.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||0;if(segments.length===0)return newCursor;let last=segments[segments.length-1];if(isAtomic?.(last.segment))newCursor-=last.segment.length;else if(last.isWordLike){let segment=last.segment,matches=[...segment.matchAll(new RegExp(PUNCTUATION_REGEX,"g"))];if(matches.length<=0)newCursor-=segment.length;else{let lastMatch=matches[matches.length-1];newCursor-=segment.length-(lastMatch.index+lastMatch[0].length)}}else for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&!segments[segments.length-1]?.isWordLike&&!isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;return newCursor}function findWordForward(text,cursor,options2){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options2?.segment,isAtomic=options2?.isAtomicSegment,iterator=(segmentFn?segmentFn(textAfterCursor):wordSegmenter2.segment(textAfterCursor))[Symbol.iterator](),next=iterator.next(),newCursor=cursor;for(;!next.done&&!isAtomic?.(next.value.segment)&&isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();if(next.done)return newCursor;if(isAtomic?.(next.value.segment))newCursor+=next.value.segment.length;else if(next.value.isWordLike)newCursor+=PUNCTUATION_REGEX.exec(next.value.segment)?.index??next.value.segment.length;else for(;!next.done&&!isAtomic?.(next.value.segment)&&!next.value.isWordLike&&!isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();return newCursor}var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(items,maxVisible,theme2,layout={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,this.layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings();kb.matches(keyData,"tui.select.up")?(this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange()):kb.matches(keyData,"tui.select.down")?(this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange()):kb.matches(keyData,"tui.select.confirm")?this.confirmSelection():kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}confirmSelection(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");if(isSelected)return this.theme.selectedText(`${prefix}${truncatedValue2}${spacing}${truncatedDesc}`);let descText=this.theme.description(spacing+truncatedDesc);return prefix+truncatedValue2+descText}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return isSelected?this.theme.selectedText(`${prefix}${truncatedValue}`):prefix+truncatedValue}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH;return{min:Math.max(1,Math.min(rawMin,rawMax)),max:Math.max(1,Math.max(rawMin,rawMax))}}truncatePrimary(item,isSelected,maxWidth,columnWidth){let displayValue=this.getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.truncatePrimary({text:displayValue,maxWidth,columnWidth,item,isSelected}):truncateToWidth(displayValue,maxWidth,"");return truncateToWidth(truncatedValue,maxWidth,"")}getDisplayValue(item){return item.label||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter3=getWordSegmenter(),PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function segmentWithMarkers(text,baseSegmenter,validIds){if(validIds.size===0||!text.includes("[paste #"))return baseSegmenter.segment(text);let markers=[];for(let m of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m[1],10);validIds.has(id)&&markers.push({start:m.index,end:m.index+m[0].length})}if(markers.length===0)return baseSegmenter.segment(text);let baseSegments=baseSegmenter.segment(text),result=[],markerIdx=0;for(let seg of baseSegments){for(;markerIdx<markers.length&&markers[markerIdx].end<=seg.index;)markerIdx++;let marker=markerIdx<markers.length?markers[markerIdx]:null;if(marker&&seg.index>=marker.start&&seg.index<marker.end){if(seg.index===marker.start){let markerText=text.slice(marker.start,marker.end);result.push({segment:markerText,index:marker.start,input:text})}}else result.push(seg)}return result}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isPasteMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.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-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(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,options2={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options2.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options2.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(){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){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(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.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(`
69
- `);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){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)),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);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),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?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(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-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)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(data){let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}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);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.continueCompletionAfter(selected)}return}if(kb.matches(data,"tui.select.confirm")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.continueCompletionAfter(selected);return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();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.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
70
- `&&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()||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(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){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,[...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.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(`
71
- `)}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(`
72
- `))}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.insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
73
- `).replace(/\r/g,`
74
- `).replace(/\t/g," ")}insertTextAtCursorInternal(text){if(!text)return;let normalized=this.normalizeText(text),insertedLines=normalized.split(`
75
- `),currentLine=this.state.lines[this.state.cursorLine]||"",beforeCursor=currentLine.slice(0,this.state.cursorCol),afterCursor=currentLine.slice(this.state.cursorCol);insertedLines.length===1?(this.state.lines[this.state.cursorLine]=beforeCursor+normalized+afterCursor,this.setCursorCol(this.state.cursorCol+normalized.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),beforeCursor+insertedLines[0],...insertedLines.slice(1,-1),insertedLines[insertedLines.length-1]+afterCursor,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=insertedLines.length-1,this.setCursorCol((insertedLines[insertedLines.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(char,skipUndoCoalescing){this.exitHistoryBrowsing(),skipUndoCoalescing||((isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let line=this.state.lines[this.state.cursorLine]||"",before=line.slice(0,this.state.cursorCol),after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let decodedText=pastedText.replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
76
- `||char.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(filteredText)){let currentLine=this.state.lines[this.state.cursorLine]||"",charBeforeCursor=this.state.cursorCol>0?currentLine[this.state.cursorCol-1]:"";charBeforeCursor&&/\w/.test(charBeforeCursor)&&(filteredText=` ${filteredText}`)}let pastedLines=filteredText.split(`
77
- `),totalChars=filteredText.length;if(pastedLines.length>10||totalChars>1e3){this.pasteCounter++;let pasteId=this.pasteCounter;this.pastes.set(pasteId,filteredText);let marker=pastedLines.length>10?`[paste #${pasteId} +${pastedLines.length} lines]`:`[paste #${pasteId} ${totalChars} chars]`;this.insertTextAtCursorInternal(marker);return}if(pastedLines.length===1){this.insertTextAtCursorInternal(filteredText);return}this.insertTextAtCursorInternal(filteredText)}addNewLine(){this.cancelAutocomplete(),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,"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(`
78
- `)).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(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.lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{let x=Number(idGroup);return x<=targetId?fullMatch:`[paste #${x-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.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(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(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let segments=[...this.segment(logicalLine,"grapheme")];for(let seg of segments){if(seg.index>this.state.cursorCol)break;if(!(seg.segment.length<=1)&&this.state.cursorCol<seg.index+seg.segment.length){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
79
- `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let 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)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cursorCol);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
80
- `,{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)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
81
- `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let 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)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordBackwards();let deleteFrom=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(deleteFrom,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,deleteFrom)+currentLine.slice(this.state.cursorCol),this.setCursorCol(deleteFrom)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
82
- `,{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);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=[...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.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]||"",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];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.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.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.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),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.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();let lines=text.split(`
83
- `);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]||"");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(`
84
- `);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.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list2=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list2.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText()),this.continueCompletionAfter(selected)},list2}continueCompletionAfter(item){"continueCompletion"in item&&item.continueCompletion===!0&&this.tryTriggerAutocomplete()}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options2){if(!this.autocompleteProvider||options2.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options2);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options2)},debounceMs);return}this.startAutocompleteRequest(startToken,options2)}async startAutocompleteRequest(startToken,options2){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options2){if(options2.explicitTab||options2.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options2){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options2.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options2.force&&options2.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options2.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var LAYOUT_NODE=Symbol.for("@draht/tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options2={}){super(),this.gap=normalizeSize(options2.gap,0),this.align=options2.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options2={}){super.addChild(component),this.entries.push({component,...options2.basis===void 0?{}:{basis:options2.basis},...options2.grow===void 0?{}:{grow:normalizeSize(options2.grow,0)},...options2.shrink===void 0?{}:{shrink:normalizeSize(options2.shrink,1)},...options2.minSize===void 0?{}:{minSize:normalizeSize(options2.minSize,0)},...options2.maxSize===void 0?{}:{maxSize:normalizeSize(options2.maxSize,Number.MAX_SAFE_INTEGER)},...options2.visible===void 0?{}:{visible:options2.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options2={}){super(children,options2)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x,childWidth,safeWidth))}x+=childWidth+this.gap}return result}};var imageTranscoder,pngCache=new Map;function setImageTranscoder(transcoder){imageTranscoder=transcoder,pngCache.clear()}function toPng(base64Data,mimeType){if(!imageTranscoder)return null;let cached=pngCache.get(base64Data),png=cached===void 0?imageTranscoder(base64Data,mimeType):cached;return pngCache.delete(base64Data),pngCache.set(base64Data,png),pngCache.size>32&&pngCache.delete(pngCache.keys().next().value),png}var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options2={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options2,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options2.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(),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.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(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;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options2={}){this.prompt=options2.prompt??"> ",this.placeholder=options2.placeholder??"",this.placeholderStyle=options2.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}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(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===`
85
- `){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.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1];this.cursor-=lastGrapheme?lastGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0];this.cursor+=firstGrapheme?firstGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let kittyPrintable=decodeKittyPrintable(data);if(kittyPrintable!==void 0){this.insertCharacter(kittyPrintable);return}[...data].some(ch=>{let code=ch.charCodeAt(0);return code<32||code===127||code>=128&&code<=159})||this.insertCharacter(data)}handleMouse(event){if(event.type!=="press"||event.button!=="left"||event.y!==0)return;let visibleColumn=Math.max(0,event.x-2),targetColumn=this.renderedStartColumn+visibleColumn,currentColumn=0;this.cursor=this.value.length;for(let grapheme of segmenter.segment(this.value)){let nextColumn=currentColumn+visibleWidth(grapheme.segment);if(targetColumn<nextColumn){this.cursor=grapheme.index;break}currentColumn=nextColumn}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(char){(isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+char+this.value.slice(this.cursor),this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor-graphemeLength)+this.value.slice(this.cursor),this.cursor-=graphemeLength}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+graphemeLength)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let deletedText=this.value.slice(0,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let deletedText=this.value.slice(this.cursor);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordBackwards();let deleteFrom=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(deleteFrom,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,deleteFrom)+this.value.slice(this.cursor),this.cursor=deleteFrom}deleteWordForward(){if(this.cursor>=this.value.length)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordForwards();let deleteTo=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(this.cursor,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(deleteTo)}yank(){let text=this.killRing.peek();text&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let prevText=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-prevText.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=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 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.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=this.cursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(this.value);if(totalWidth<availableWidth)visibleText=this.value;else{let scrollWidth=this.cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(this.value.slice(0,this.cursor));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(this.value,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(this.value,startCol,Math.max(0,cursorCol-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-visualLength));return[this.prompt+textWithCursor+padding]}};var CJK="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda}\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",cjkTest=new RegExp(`[${CJK}]`,"u"),punctuationCjk=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${CJK}])`,"u");function buildRDelimAst(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${punct}(\\*+)(?=[\\s]|$)|${notPunctSpace}(\\*+)(?!\\*)(?=${punctSpace}|$)|(?!\\*)${punctSpace}(\\*+)(?=${notPunctSpace})|[\\s](\\*+)(?!\\*)(?=${punct})|(?!\\*)${punct}(\\*+)(?!\\*)(?=${punct})|${notPunctSpace}(\\*+)(?=${notPunctSpace})`,"gu")}function buildRDelimUnd(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${punct}(_+)(?=[\\s]|$)|${notPunctSpace}(_+)(?!_)(?=${punctSpace}|$)|(?!_)${punctSpace}(_+)(?=${notPunctSpace})|[\\s](_+)(?!_)(?=${punct})|(?!_)${punct}(_+)(?!_)(?=${punct})`,"gu")}function buildRDelimDel(punct,punctSpace,notPunctSpace){return new RegExp(`^[^~]+(?=[^~])|(?!~)${punct}(~~?)(?=[\\s]|$)|${notPunctSpace}(~~?)(?!~)(?=${punctSpace}|$)|(?!~)${punctSpace}(~~?)(?=${notPunctSpace})|[\\s](~~?)(?!~)(?=${punct})|(?!~)${punct}(~~?)(?!~)(?=${punct})|${notPunctSpace}(~~?)(?=${notPunctSpace})`,"gu")}var cjkPunct=`[\\p{P}\\p{S}${CJK}]`,cjkPunctSpace=`[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpace=`[^\\s\\p{P}\\p{S}${CJK}]`,cjkDelPunct=`(?![*_])[\\p{P}\\p{S}${CJK}]`,cjkDelPunctSpace=`(?![*_])[\\s\\p{P}\\p{S}${CJK}]`,cjkDelNotPunctSpace=`(?:[^\\s\\p{P}\\p{S}${CJK}]|[*_])`,cjkPunctGfm=`(?!~)[\\p{P}\\p{S}${CJK}]`,cjkPunctSpaceGfm=`(?!~)[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpaceGfm=`(?:[^\\s\\p{P}\\p{S}${CJK}]|~)`,emStrongRDelimAstCjk=buildRDelimAst(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),emStrongRDelimAstCjkGfm=buildRDelimAst(cjkPunctGfm,cjkPunctSpaceGfm,cjkNotPunctSpaceGfm),emStrongRDelimUndCjk=buildRDelimUnd(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),delRDelimCjk=buildRDelimDel(cjkDelPunct,cjkDelPunctSpace,cjkDelNotPunctSpace);function isPrevCharCjk(prevChar,maskedSrc,src){let prevIsCjk=punctuationCjk.test(prevChar);if(!prevIsCjk&&prevChar){let prevIdx=maskedSrc.length-src.length;if(prevIdx>=1){let idx=prevIdx-1,code=maskedSrc.charCodeAt(idx);if(code>=65024&&code<=65038&&idx>=1&&(idx--,code=maskedSrc.charCodeAt(idx)),(code&64512)===56320&&idx>=1){let cp=maskedSrc.codePointAt(idx-1);cp!==void 0&&cp>65535&&(cp>=917760&&cp<=917999?prevIsCjk=!0:prevIsCjk=cjkTest.test(String.fromCodePoint(cp)))}else prevIsCjk=cjkTest.test(String.fromCharCode(code))}}return prevIsCjk}function isCjkAdjacentToDelimiter(rightMatch,clippedMaskedSrc){if(!(rightMatch[1]||rightMatch[2]||rightMatch[3]||rightMatch[4]))return!1;let charBefore=String.fromCodePoint(rightMatch[0].codePointAt(0)),afterPos=rightMatch.index+rightMatch[0].length,charAfter=afterPos<clippedMaskedSrc.length?String.fromCodePoint(clippedMaskedSrc.codePointAt(afterPos)):"";return cjkTest.test(charBefore)||cjkTest.test(charAfter)}function usesModernEmStrongLayout(match){return match.length>=5}function hasEmStrongLeadContent(match){return!!(match[1]||match[2]||match[3]||match[4])}function isEmStrongUnderscoreWordChar(match){return usesModernEmStrongLayout(match)?!!match[4]:!!match[3]}function getEmStrongOpeningPunctuation(match){return usesModernEmStrongLayout(match)?match[1]||match[3]||"":match[1]||match[2]||""}function markedCjkFriendly(){return{tokenizer:{emStrong(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.emStrongLDelim.exec(src);if(!match)return!1;let modernEmStrongLayout=usesModernEmStrongLayout(match);if(modernEmStrongLayout&&!hasEmStrongLeadContent(match))return;if(isEmStrongUnderscoreWordChar(match)&&prevChar.match(rules.other.unicodeAlphaNumeric))return!1;let nextChar=getEmStrongOpeningPunctuation(match),prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=[...match[0]].length-1,rDelim,rLength,delimTotal=lLength,midDelimTotal=0,prevCharIsSameDelimiter=modernEmStrongLayout&&prevChar===match[0][0],isGfm=rules.inline.emStrongRDelimAst.source.includes("(?!~)"),endReg;match[0][0]==="*"?endReg=isGfm?emStrongRDelimAstCjkGfm:emStrongRDelimAstCjk:endReg=emStrongRDelimUndCjk,endReg.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=endReg.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim)continue;rLength=[...rDelim].length;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc),isLeftOnly=!!(rMatch[3]||rMatch[4]),isBoth=!!(rMatch[5]||rMatch[6]);if(isLeftOnly&&!isCjkAdjacent){delimTotal+=rLength;continue}if(isBoth||isCjkAdjacent){if(lLength%3&&!((lLength+rLength)%3)){midDelimTotal+=rLength;continue}if(prevCharIsSameDelimiter&&isBoth)break}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal+midDelimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength);if(Math.min(lLength,rLength)%2){let text2=raw.slice(1,-1);return{type:"em",raw,text:text2,tokens:this.lexer.inlineTokens(text2)}}let text=raw.slice(2,-2);return{type:"strong",raw,text,tokens:this.lexer.inlineTokens(text)}}}},del(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.delLDelim.exec(src);if(!match)return!1;let nextChar=match[1]||"",prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=[...match[0]].length-1,rDelim,rLength,delimTotal=lLength;delRDelimCjk.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=delRDelimCjk.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim||(rLength=[...rDelim].length,rLength!==lLength))continue;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc);if((rMatch[3]||rMatch[4])&&!isCjkAdjacent){delimTotal+=rLength;continue}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength),text=raw.slice(lLength,-lLength);return{type:"del",raw,text,tokens:this.lexer.inlineTokens(text)}}}}}}}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",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",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",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},NAMED_OPERATORS=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),LIMIT_OPERATORS=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),DISPLAY_LIMIT_SYMBOLS=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),RELATION_COMMANDS=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),NEGATED_SYMBOLS={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},BLACKBOARD={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},SUPERSCRIPTS={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPTS={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},SPACING_COMMANDS=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),NEGATIVE_SPACING_COMMANDS=new Set(["!","negmedspace","negthickspace","negthinspace"]),NEGATIVE_SPACE="\0",FONT_SWITCH_COMMANDS=new Set(["bf","cal","it","rm","sf","sl","tt"]),IGNORED_COMMANDS=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),SIZE_COMMANDS=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),PLAIN_WRAPPERS=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),ACCENTS={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function normalizeScriptValue(value){return value.trim().replace(/\s*([=+-])\s*/g,"$1")}function formatUnicodeScript(value,kind){return replaceCharacters(normalizeScriptValue(value),kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS)}function formatScript(value,kind){value=normalizeScriptValue(value);let unicode=formatUnicodeScript(value,kind);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";return Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value)?`${prefix}${value}`:`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="\u221A"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}var NAMED_OPERATOR_START="\u{F0004}",NAMED_OPERATOR_END="\u{F0005}",NAMED_OPERATOR_LEFT_SPACING_PATTERN=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,NAMED_OPERATOR_RIGHT_SPACING_PATTERN=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
86
- `).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
87
- `).trim()}var LAYOUT_MARKER_START="\u{F0000}",LAYOUT_MARKER_END="\u{F0001}",LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}/gu,TRAILING_LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}$/u,PROTECTED_SPACE="\u{F0002}";function padLayoutLine(line,width,centered=!1){let padding=Math.max(0,width-visibleWidth(line)),left=centered?Math.floor(padding/2):0;return`${" ".repeat(left)}${line}${" ".repeat(padding-left)}`}function joinLayouts(layouts){if(layouts.length===0)return{lines:[""],width:0,baseline:0};let baseline=Math.max(...layouts.map(layout=>layout.baseline)),below=Math.max(...layouts.map(layout=>layout.lines.length-layout.baseline-1)),lines=[];for(let row=0;row<=baseline+below;row++){let line="";for(let layout of layouts){let sourceRow=row-baseline+layout.baseline;line+=sourceRow>=0&&sourceRow<layout.lines.length?padLayoutLine(layout.lines[sourceRow]??"",layout.width):" ".repeat(layout.width)}lines.push(line.trimEnd())}return{lines,width:layouts.reduce((width,layout)=>width+layout.width,0),baseline}}function renderLayout(source,nodes){let renderedLines=[],firstBaseline=0;for(let sourceLine of source.split(`
88
- `)){let layouts=[],position=0,previousNode;for(let match of sourceLine.matchAll(LAYOUT_MARKER_PATTERN)){let index=match.index,node=nodes[Number(match[1])];if(node){if(index>position){let sliced=sourceLine.slice(position,index),trimmed=(previousNode?sliced.trimStart():sliced).trimEnd(),preserveLeadingSpace=previousNode?.type==="matrix"&&/^\s/.test(sliced),preserveTrailingSpace=node.type==="matrix"&&/\s$/.test(sliced),text=trimmed?`${preserveLeadingSpace?" ":""}${trimmed}${preserveTrailingSpace?" ":""}`:preserveLeadingSpace||preserveTrailingSpace?" ":"";layouts.push({lines:[text],width:visibleWidth(text),baseline:0})}if(node.type==="fraction"){let numerator=renderLayout(node.numerator,nodes),denominator=renderLayout(node.denominator,nodes),contentWidth=Math.max(numerator.width,denominator.width,1),width=contentWidth+2;layouts.push({lines:[...numerator.lines.map(line=>padLayoutLine(line,width,!0)),` ${"\u2500".repeat(contentWidth)} `,...denominator.lines.map(line=>padLayoutLine(line,width,!0))],width,baseline:numerator.lines.length})}else if(node.type==="operator"){let contentWidth=Math.max(visibleWidth(node.operator),node.lower===void 0?0:visibleWidth(node.lower),node.upper===void 0?0:visibleWidth(node.upper)),lines=[];node.upper!==void 0&&lines.push(`${padLayoutLine(node.upper,contentWidth,!0)} `),lines.push(`${padLayoutLine(node.operator,contentWidth,!0)} `),node.lower!==void 0&&lines.push(`${padLayoutLine(node.lower,contentWidth,!0)} `),layouts.push({lines,width:contentWidth+1,baseline:node.upper===void 0?0:1})}else if(node.type==="script"){let upper=node.upper===void 0?void 0:renderLayout(node.upper,nodes),lower=node.lower===void 0?void 0:renderLayout(node.lower,nodes),width=Math.max(upper?.width??0,lower?.width??0);layouts.push({lines:[...upper?.lines.map(line=>padLayoutLine(line,width))??[]," ".repeat(width),...lower?.lines.map(line=>padLayoutLine(line,width))??[]],width,baseline:upper?.lines.length??0})}else{let width=Math.max(0,...node.lines.map(line=>visibleWidth(line)));layouts.push({lines:node.lines.map(line=>padLayoutLine(line,width)),width,baseline:node.baseline})}position=index+match[0].length,previousNode=node}}if(position<sourceLine.length){let sliced=sourceLine.slice(position),trimmed=previousNode?sliced.trimStart():sliced,text=previousNode?.type==="matrix"&&/^\s/.test(sliced)?` ${trimmed}`:trimmed;layouts.push({lines:[text],width:visibleWidth(text),baseline:0})}let lineLayout=joinLayouts(layouts);renderedLines.length===0&&(firstBaseline=lineLayout.baseline),renderedLines.push(...lineLayout.lines)}return{lines:renderedLines,width:Math.max(0,...renderedLines.map(line=>visibleWidth(line))),baseline:firstBaseline}}var LatexParser=class _LatexParser{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(source,layoutNodes,display){this.source=source,this.layoutNodes=layoutNodes,this.display=display}render(){let rendered=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return normalizeOutput(rendered)}parseSequence(endCharacter){let result="";for(;this.position<this.source.length;){let character=this.source[this.position];if(endCharacter&&character===endCharacter)return this.position++,result;if(character==="}")return this.supported=!1,result;if(character==="{"){this.position++,result+=this.parseSequence("}");continue}if(character==="\\"){let command=this.parseCommand();command===NEGATIVE_SPACE?(result=result.trimEnd(),result.endsWith(NAMED_OPERATOR_END)&&(result=result.slice(0,-NAMED_OPERATOR_END.length))):result+=command;continue}if(character==="^"||character==="_"){this.position++,result=result.trimEnd();let script=this.parseScripts(character);result.endsWith(NAMED_OPERATOR_END)?result=`${result.slice(0,-NAMED_OPERATOR_END.length)}${script}${NAMED_OPERATOR_END}`:result+=script;continue}if(/\s/.test(character)){result+=this.parseWhitespace();continue}if(character==="="||character==="<"||character===">"){result=`${result.trimEnd()} ${character} `,this.position++;continue}if(character==="&"){this.position++;continue}if(character==="~"){this.position++,result+=" ";continue}if(character==="."){let marker=TRAILING_LAYOUT_MARKER_PATTERN.exec(result),node=marker?this.layoutNodes[Number(marker[1])]:void 0;if(node?.type==="matrix"){let lastLine=node.lines.length-1;node.lines[lastLine]=`${node.lines[lastLine]??""}${character}`,this.position++;continue}}result+=character,this.position++}return endCharacter&&(this.supported=!1),result}parseScripts(initialMarker){let scripts={},order=[],parse=marker=>{let kind=marker==="_"?"sub":"sup";this.scriptDepth++;try{scripts[kind]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}order.push(kind)};parse(initialMarker);let nextPosition=this.position;for(;nextPosition<this.source.length&&/\s/.test(this.source[nextPosition]??"");)nextPosition++;let nextMarker=this.source[nextPosition];(nextMarker==="^"||nextMarker==="_")&&nextMarker!==initialMarker&&(this.position=nextPosition+1,parse(nextMarker));let subUnicode=scripts.sub===void 0?void 0:formatUnicodeScript(scripts.sub,"sub"),supUnicode=scripts.sup===void 0?void 0:formatUnicodeScript(scripts.sup,"sup"),canUseLayout=![scripts.sub,scripts.sup].some(value=>value!==void 0&&(value.includes("/")||!value.includes(LAYOUT_MARKER_START)&&Array.from(value).length>1&&!/[A-Z*∗]/.test(value)));if(!(this.display&&canUseLayout&&(this.scriptDepth>0||scripts.sub!==void 0&&subUnicode===void 0||scripts.sup!==void 0&&supUnicode===void 0)))return order.map(kind=>kind==="sub"?subUnicode??formatScript(scripts.sub??"",kind):supUnicode??formatScript(scripts.sup??"",kind)).join("");let index=this.layoutNodes.push({type:"script",lower:scripts.sub===void 0?void 0:normalizeOutput(scripts.sub),upper:scripts.sup===void 0?void 0:normalizeOutput(scripts.sup)})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return" "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=!1,"";let command="",first=this.source[this.position]??"";if(first===`
89
- `||first==="\r")return this.position++,first==="\r"&&this.source[this.position]===`
90
- `&&this.position++," ";if(/[A-Za-z]/.test(first)){let start=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;command=this.source.slice(start,this.position)}else command=first,this.position++;if(command==="\\")return`
91
- `;if(SPACING_COMMANDS.has(command))return" ";if(NEGATIVE_SPACING_COMMANDS.has(command))return NEGATIVE_SPACE;if(FONT_SWITCH_COMMANDS.has(command)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return""}if(IGNORED_COMMANDS.has(command))return"";if(command==="{"||command==="}"||command==="$"||command==="%"||command==="#"||command==="_"||command==="&")return command;if(command==="|")return"\u2016";if(command==="not"){let value=this.parseRequiredArgument(!1).trim(),negated=NEGATED_SYMBOLS[value];if(negated!==void 0)return` ${negated} `;let characters=Array.from(value);return characters.length===0?(this.supported=!1,""):` ${characters[0]}\u0338${characters.slice(1).join("")} `}if(LIMIT_OPERATORS.has(command))return this.parseOperator(command,"bracket",!0,!0);let symbol=SYMBOLS[command];if(symbol!==void 0)return DISPLAY_LIMIT_SYMBOLS.has(command)?this.parseOperator(symbol,"script",!0):command==="cdot"||command==="times"||RELATION_COMMANDS.has(command)?` ${symbol} `:symbol;if(NAMED_OPERATORS.has(command))return`${NAMED_OPERATOR_START}${command}${NAMED_OPERATOR_END}`;if(SIZE_COMMANDS.has(command))return"";if(command==="left"||command==="middle"||command==="right")return this.source[this.position]==="."&&this.position++,"";if(command==="frac"||command==="dfrac"||command==="tfrac"){let shouldStack=this.display&&this.stackFractions&&command!=="tfrac",numerator=this.parseRequiredArgument(!shouldStack),denominator=this.parseRequiredArgument(!shouldStack);if(shouldStack){let index=this.layoutNodes.push({type:"fraction",numerator:normalizeOutput(numerator),denominator:normalizeOutput(denominator)})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}return formatFraction(numerator,denominator)}if(command==="sqrt"){let degree=this.parseOptionalArgument()?.trim(),value=this.parseRequiredArgument();return degree===void 0||degree==="2"?formatRoot(value):degree==="3"?formatRoot(value,"\u221B"):degree==="4"?formatRoot(value,"\u221C"):`${formatScript(degree,"sup")}${formatRoot(value)}`}if(command==="boxed"||command==="fbox")return`[${this.parseRequiredArgument().trim()}]`;if(command==="binom"||command==="dbinom"||command==="tbinom")return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let accent=ACCENTS[command];if(accent!==void 0){let value=this.parseRequiredArgument();return Array.from(value).length===1?`${value}${accent}`:`${command}(${value})`}if(command==="mathbb"){let value=this.parseRequiredArgument();return Array.from(value,character=>BLACKBOARD[character]??character).join("")}if(command==="operatorname"){let starred=this.source[this.position]==="*";starred&&this.position++;let operator=normalizeOutput(this.parseRequiredArgument()).trim();return this.parseOperator(operator,"bracket",starred,!0)}if(command==="mod"||command==="bmod")return" mod ";if(command==="pmod"||command==="pod"){let value=this.parseRequiredArgument().trim();return command==="pmod"?` (mod ${value})`:` (${value})`}if(command==="overset"||command==="stackrel"){let upper=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${formatScript(upper,"sup")}`}if(command==="underset"){let lower=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${formatScript(lower,"sub")}`}if(PLAIN_WRAPPERS.has(command)){let value=this.parseRequiredArgument();return command.startsWith("text")||command==="mbox"?value:value.trim()}return command==="begin"?this.parseEnvironment():command==="end"?(this.supported=!1,""):(this.supported=!1,`\\${command}`)}parseOperator(operator,inlineLowerStyle,displayLimits,spaced=!1){let useDisplayLimits=displayLimits,modifierPosition=this.position;for(;modifierPosition<this.source.length&&/[ \t]/.test(this.source[modifierPosition]??"");)modifierPosition++;let modifier=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(modifierPosition));modifier&&(useDisplayLimits=modifier[1]==="limits",this.position=modifierPosition+modifier[0].length);let lower,upper;for(;;){let scriptPosition=this.position;for(;scriptPosition<this.source.length&&/[ \t]/.test(this.source[scriptPosition]??"");)scriptPosition++;let kind=this.source[scriptPosition];if(kind!=="_"&&kind!=="^")break;this.position=scriptPosition+1;let value=normalizeOutput(this.parseRequiredArgument(!1)).replaceAll(" ","");kind==="_"?(lower!==void 0&&(this.supported=!1),lower=value):(upper!==void 0&&(this.supported=!1),upper=value)}if(this.display&&useDisplayLimits&&(lower!==void 0||upper!==void 0)){let index=this.layoutNodes.push({type:"operator",operator,lower,upper})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}let rendered=operator;return lower!==void 0&&(rendered+=inlineLowerStyle==="bracket"?`[${lower}]`:formatScript(lower,"sub")),upper!==void 0&&(rendered+=formatScript(upper,"sup")),spaced?` ${rendered} `:rendered}parseRequiredArgument(stackFractions=!0){let previousStackFractions=this.stackFractions;this.stackFractions=previousStackFractions&&stackFractions;let value=this.parseRequiredArgumentValue();return this.stackFractions=previousStackFractions,value}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=!1,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let value=this.source[this.position]??"";return this.position++,value}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let end=this.source.indexOf("]",this.position+1);if(end<0){this.supported=!1;return}let value=this.source.slice(this.position+1,end);return this.position=end+1,this.renderNested(value)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=!1;return}let start=++this.position,depth=1;for(;this.position<this.source.length;){let character=this.source[this.position];if(character==="\\"){this.position+=2;continue}if(character==="{"&&depth++,character==="}"&&depth--,depth===0){let value=this.source.slice(start,this.position);return this.position++,value}this.position++}this.supported=!1}splitEnvironmentRows(body){return body.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let environment=this.readRawGroup();if(!environment)return"";let endMarker=`\\end{${environment}}`,end=this.source.indexOf(endMarker,this.position);if(end<0)return this.supported=!1,"";let body=this.source.slice(this.position,end);if(this.position=end+endMarker.length,environment==="equation"||environment==="equation*"||environment==="displaymath")return this.renderNested(body).trim();if(environment==="aligned"||environment==="align"||environment==="align*"||environment==="alignedat"||environment==="alignat"||environment==="alignat*"||environment==="gather"||environment==="gathered"||environment==="multline"||environment==="multline*"||environment==="split"){let alignedAt=["alignedat","alignat","alignat*"].includes(environment),alignedBody=alignedAt?body.replace(/^\s*\{[^}]*\}/,""):body;return this.splitEnvironmentRows(alignedBody).map(row=>{let cells=row.split("&"),source=alignedAt?Array.from({length:Math.ceil(cells.length/2)},(_,index)=>cells.slice(index*2,index*2+2).join("")).join(" "):cells.join("");return this.renderNested(source).trim()}).filter(Boolean).join(`
92
- `)}if(environment==="cases"||environment==="cases*")return this.renderCases(body);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(environment)){let matrixBody=environment==="array"?body.replace(/^\s*\{[^}]*\}/,""):body;return this.renderMatrix(environment,matrixBody)}return this.supported=!1,body}renderCases(body){let rows=this.splitEnvironmentRows(body).map(row=>row.split("&").map(cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),valueWidth=Math.max(0,...rows.map(row=>visibleWidth((row[0]??"").replace(/,\s*$/,"")))),contents=rows.map(row=>{let value=(row[0]??"").replace(/,\s*$/,""),condition=row[1]??"";if(!condition)return value;let conditionPrefix=/^(?:if|when|for|otherwise)\b/i.test(condition)?" ":" if ";return`${value}${PROTECTED_SPACE.repeat(valueWidth-visibleWidth(value))}${conditionPrefix}${condition}`});if(contents.length<=1)return contents.length===0?"":`\u23A7 ${contents[0]}`;let middle=Math.floor(contents.length/2),visualRows=[...contents];contents.length%2===0&&visualRows.splice(middle,0,void 0);let lines=visualRows.map((content,index2)=>{let delimiter=index2===0?"\u23A7":index2===visualRows.length-1?"\u23A9":"\u23A8";return content===void 0?delimiter:`${delimiter} ${content}`}),index=this.layoutNodes.push({type:"matrix",lines,baseline:middle})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}renderMatrix(environment,body){let matrix=this.splitEnvironmentRows(body).map(row=>row.split("&").map(cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),columnCount=Math.max(0,...matrix.map(row=>row.length)),columnWidths=Array.from({length:columnCount},(_,column)=>Math.max(0,...matrix.map(row=>visibleWidth(row[column]??"")))),rows=matrix.map(row=>Array.from({length:columnCount},(_,column)=>{let cell=row[column]??"";return`${cell}${PROTECTED_SPACE.repeat(Math.max(0,(columnWidths[column]??0)-visibleWidth(cell)))}`}).join(" \u2502 ")),lines;if(environment==="array"||environment==="matrix"||environment==="smallmatrix")lines=rows;else{let delimiter={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[environment];if(!delimiter)return this.supported=!1,rows.join(`
93
- `);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(source,stackFractions=!0){let rendered=new _LatexParser(source,this.layoutNodes,this.display&&stackFractions).render();return rendered===void 0?(this.supported=!1,source):rendered}};function renderLatex(source,options2={}){let layoutNodes=[],rendered=new LatexParser(source,layoutNodes,options2.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.slice(indentation).trimEnd()).join(`
94
- `).trimEnd().replaceAll(PROTECTED_SPACE," ")}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,StrictStrikethroughTokenizer=class extends _Tokenizer{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(source,index){let backslashes=0;for(let position=index-1;position>=0&&source[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source,closing,start){let index=source.indexOf(closing,start);for(;index>=0&&isEscaped(source,index);)index=source.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source)}function tokenizeInlineLatex(source){let opening="",closing="";if(source.startsWith("$$"))opening="$$",closing="$$";else if(source.startsWith("\\("))opening="\\(",closing="\\)";else if(source.startsWith("\\["))opening="\\[",closing="\\]";else if(source.startsWith("$")&&!/^\$\s/.test(source))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source.slice(opening.length,closingIndex))||/^\d/.test(source.slice(closingIndex+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex+1))||source.slice(opening.length,closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source.slice(opening.length);return opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource)?{type:"latex",raw:source,text:pendingSource,pending:!0}:void 0}let text=source.slice(opening.length,closingIndex);return!text||text.includes(`
95
- `)?void 0:{type:"latex",raw:source.slice(0,closingIndex+closing.length),text}}var TABLE_DELIMITER_ROW_REGEX=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function containsTableStart(source){let lines=source.split(`
96
- `);for(let index=0;index<lines.length-1;index++){let delimiterRow=lines[index+1];if((delimiterRow.includes("|")||lines[index].includes("|"))&&TABLE_DELIMITER_ROW_REGEX.test(delimiterRow))return!0}return!1}function tokenizeBlockLatex(source){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);if(dollarMatch?.[1]&&!containsTableStart(dollarMatch[1]))return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);if(bracketMatch?.[1]&&!containsTableStart(bracketMatch[1]))return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingBracket?.[1]&&!containsTableStart(pendingBracket[1]))return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1])&&!containsTableStart(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);return match?match.index+(match[0].startsWith(`
97
- `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source){let indices=[source.indexOf("$"),source.indexOf("\\("),source.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(token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
98
- `).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 Marked;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});markdownParser.use({tokenizer:{emStrong:markedCjkFriendly().tokenizer?.emStrong},extensions:[...LATEX_MARKDOWN_EXTENSIONS]});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options2){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options2?{...options2}:{}}setText(text){this.text=text,this.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;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=text.replace(/\t/g," "),cached=this.cachedTokens?.deref(),tokens=cached?.source===normalizedText?cached.tokens:void 0;tokens||(tokens=markdownParser.lexer(normalizedText),trimPartialClosingFences(tokens),this.cachedTokens=new WeakRef({source:normalizedText,tokens}));let renderedLines=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],nextToken=tokens[i+1],tokenLines=this.renderToken(token,contentWidth,nextToken?.type);for(let tokenLine of tokenLines)renderedLines.push(tokenLine)}let wrappedLines=[];for(let line of renderedLines)if(isImageLine(line))wrappedLines.push(line);else for(let wrappedLine of wrapTextWithAnsi(line,contentWidth))wrappedLines.push(wrappedLine);let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,contentLines=[];for(let line of wrappedLines){if(isImageLine(line)){contentLines.push(line);continue}let lineWithMargins=leftMargin+line+rightMargin;if(bgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}let result=emptyLines.concat(contentLines,emptyLines);return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){let lines=[];switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text,{display:!0})??latexToken.raw.trim():latexToken.raw.trim();for(let line of rendered.split(`
99
- `))lines.push(this.applyDefaultStyle(line));nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"code":{let indent=this.theme.codeBlockIndent??" ";if(lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`)),this.theme.highlightCode){let highlightedLines=this.theme.highlightCode(token.text,token.lang);for(let hlLine of highlightedLines)lines.push(`${indent}${hlLine}`)}else{let codeLines=token.text.split(`
100
- `);for(let codeLine of codeLines)lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}lines.push(this.theme.codeBlockBorder("```")),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"list":{let listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines);break}case"table":{let tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{let quoteStyle=text=>this.theme.quote(this.theme.italic(text)),quoteStylePrefix=this.getStylePrefix(quoteStyle),applyQuoteStyle=line=>{if(!quoteStylePrefix)return quoteStyle(line);let lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)},quoteContentWidth=Math.max(1,width-2),quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix},quoteTokens=token.tokens||[],renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){let quoteToken=quoteTokens[i],nextQuoteToken=quoteTokens[i+1];renderedQuoteLines.push(...this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();for(let quoteLine of renderedQuoteLines){let styledLine=applyQuoteStyle(quoteLine),wrappedLines=wrapTextWithAnsi(styledLine,quoteContentWidth);for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(token.raw.trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),{applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
101
- `).map(segment=>applyText(segment)).join(`
102
- `);for(let token of tokens)switch(token.type){case"latex":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text)??latexToken.raw:latexToken.raw;result+=applyTextWithNewlines(rendered);break}case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":token.tokens&&token.tokens.length>0?result+=this.renderInlineTokens(token.tokens,resolvedStyleContext):result+=applyTextWithNewlines(token.text);break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{let boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{let italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{let linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext),styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks)result+=hyperlink(styledLink,token.href)+stylePrefix;else{let hrefForComparison=token.href.startsWith("mailto:")?token.href.slice(7):token.href;token.text===token.href||token.text===hrefForComparison?result+=styledLink+stylePrefix:result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}break}case"br":result+=`
103
- `;break;case"del":{let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":"raw"in token&&typeof token.raw=="string"&&(result+=applyTextWithNewlines(token.raw));break;default:"text"in token&&typeof token.text=="string"&&(result+=applyTextWithNewlines(token.text))}for(;stylePrefix&&result.endsWith(stylePrefix);)result=result.slice(0,-stylePrefix.length);return result}getOrderedListMarker(item){let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){let match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){let lines=[],indent=" ".repeat(depth),startNumber=typeof token.start=="number"?token.start:1;for(let i=0;i<token.items.length;i++){let item=token.items[i],isLastItem=i===token.items.length-1,bullet2=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ",taskMarker=item.task?`[${item.checked?"x":" "}] `:"",marker=bullet2+taskMarker,firstPrefix=indent+this.theme.listBullet(marker),continuationPrefix=indent+" ".repeat(visibleWidth(marker)),itemWidth=Math.max(1,width-visibleWidth(firstPrefix)),renderedAnyLine=!1;for(let itemToken of item.tokens){if(itemToken.type==="list"){lines.push(...this.renderList(itemToken,depth+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>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===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]=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=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--}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],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.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)));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(...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")}\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,options2={}){if(super(),options2.axis!==void 0&&options2.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options2.axis}`);this.child=component,this.children.push(component),this.followEnd=(options2.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options2.primary??!1,this.overscroll=options2.overscroll??"chain",this.currentScrollbar=options2.scrollbar??"hidden",this.scrollbarTrackStyle=options2.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options2.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options2.scrollbarHideDelayMs??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.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=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(active){active!==this.scrollbarActive&&(this.scrollbarActive=active,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(scrollTop,options2={}){let requested=Number.isFinite(scrollTop)?Math.trunc(scrollTop):this.currentScrollTop,maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),next=Math.max(0,Math.min(maxScrollTop,requested)),nextFollowSuppressedAtEnd=options2.disableFollow===!0&&next===maxScrollTop,nextFollowingEnd=!nextFollowSuppressedAtEnd&&this.followEnd&&next===maxScrollTop;if(next===this.currentScrollTop&&nextFollowingEnd===this.followingEnd&&nextFollowSuppressedAtEnd===this.followSuppressedAtEnd)return;let moved=next!==this.currentScrollTop;this.currentScrollTop=next,this.followingEnd=nextFollowingEnd,this.followSuppressedAtEnd=nextFollowSuppressedAtEnd,moved&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(lines){let requested=Number.isFinite(lines)?Math.trunc(lines):0;if(requested===0)return 0;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),start=this.followingEnd?maxScrollTop:this.currentScrollTop,next=Math.max(0,Math.min(maxScrollTop,start+requested)),moved=next-start,wasFollowingEnd=this.followingEnd;return this.currentScrollTop=next,this.followingEnd=this.followEnd&&next===maxScrollTop,this.followSuppressedAtEnd=!1,moved!==0&&this.markScrollbarActivity(),(moved!==0||this.followingEnd!==wasFollowingEnd)&&this.requestRenderCallback?.(),requested-moved}scrollToStart(){let changed=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let next=Math.max(0,this.contentHeight-this.currentViewportHeight),changed=this.currentScrollTop!==next||this.followingEnd!==this.followEnd;this.currentScrollTop=next,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(contentHeight,viewportHeight,requestRender){this.contentHeight=Math.max(0,Math.floor(contentHeight)),this.currentViewportHeight=Math.max(0,Math.floor(viewportHeight)),this.requestRenderCallback=requestRender;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=maxScrollTop:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,maxScrollTop)),this.currentScrollTop<maxScrollTop&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===maxScrollTop&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(_component){throw new Error("ScrollView has exactly one child")}removeChild(_component){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(width){let contentWidth=this.getContentWidth(width),lines=this.child.render(contentWidth);return contentWidth===width?lines:lines.map(line=>`${line} `)}[LAYOUT_NODE](){return{type:"scroll",component:this.child,state:this}}};var SettingsList=class{items;filteredItems;theme;selectedIndex=0;mousePressedIndex;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;navigateAfterClose=null;constructor(items,maxVisible,theme2,onChange,onCancel,options2={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options2.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems();if(kb.matches(data,"tui.select.up")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.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?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,options2)=>{selectedValue!==void 0&&(item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options2?.navigateTo&&(this.navigateAfterClose=options2.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=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(`
104
- `);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=[],options2={}){super(children,options2)}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.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="@draht/tui";function getNativeModuleCandidates(nativePath,options2={}){let moduleDir=dirname2(fileURLToPath(options2.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options2.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),"..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options2.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.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.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"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"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]$/.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){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 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]!=="\\"){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.push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options2={}){super(),this.timeoutMs=options2.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options2.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str2;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str2=`\x1B${String.fromCharCode(byte)}`}else str2=data.toString();else str2=data;if(str2.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str2,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.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.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(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.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.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$/);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.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.DRAHT_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=(()=>{let env=process.env.DRAHT_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(){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(){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(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.env.DRAHT_PROGRAM_STATUS;this.programStatusSupported=programStatusOverride==="1",this.programStatusQueryPending=programStatusOverride!=="1"&&programStatusOverride!=="0";let programStatusQuery=this.programStatusQueryPending?PROGRAM_STATUS_QUERY:"";process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${title}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);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&&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===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(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 x=Math.max(a.x,b.x),y=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,y,width:Math.max(0,right-x),height:Math.max(0,bottom-y)}}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.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(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,x,y,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.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x,y,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x,y,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,x,y-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,y,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),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(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,y,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=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,y,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y;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,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?.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-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.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.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.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<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: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.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},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,x,y){return x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function getLayoutBoxesAt(frame,x,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x,y)){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,x,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x,y)){box.scrollView&&containsPoint(box.rect,x,y)&&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 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(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.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",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,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;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="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,options2={}){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(options2.wheelScrollLines??1),this.mouseEnabled=options2.mouse??!0,this.searchMatchStyle=options2.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options2.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options2.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options2.scrollToEndIndicator,this.openUrl=options2.openUrl,this.onRightClickPaste=options2.onRightClickPaste,this.copyOnSelect=options2.copyOnSelect??!0,this.copySelection=options2.copySelection,this.addInputListener(data=>this.handleViewportInput(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(){this.clearTextSelection(),this.lastClick=void 0}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(),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=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:""}\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(options2){if(this.altScreenActive){if(this.altScreenActive=!1,options2.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));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
105
- `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
106
- \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}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={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,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x,y){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x<bounds.col||x>=bounds.col+bounds.width||y<bounds.row||y>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y-bounds.row,x-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==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.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()),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(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?.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.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.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(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,x,y,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x,y,screenX:x,screenY:y,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)||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;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,x,y){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x&&previous.y===y?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x,y},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)==="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&&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.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},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.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();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||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(x,y,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x,y)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x===geometry.column&&y>=geometry.trackTop&&y<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x,y){this.setScrollbarHover(this.getScrollbarTargetAt(x,y,!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.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=!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,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x,y){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.min(visibleBottom,y)),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,x-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.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);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--)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){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,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.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();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(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
107
- `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.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??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;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(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){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){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.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,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.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}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(root,width,height,()=>this.requestRender()));let screen=this.resolveFakeCursors(nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,"")));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.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,changedRows=screen.map((line,row)=>line!==this.previousScreen[row]),imageAnchorsNeedRedraw=screen.some((line,row)=>changedRows[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&changedRows.some(Boolean)&&screen.some((line,row)=>{let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(changedRows[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,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==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&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+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 for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,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&&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.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(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.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.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options2){if(options2.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
108
- `)}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]??"";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,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.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,computeLineDiff=targetRow=>{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);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.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
109
- `);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
110
- `);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,bufferLength-height),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=process.env.DRAHT_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"draht-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})
111
- `;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&&!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===-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}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[${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-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} < ${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.append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
112
- `.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
113
- `:"\r");let renderEnd=Math.min(lastChanged,newLines.length-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
114
- `);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
115
- \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(),"draht-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(l)}) ${l}`),""].join(`
116
- `);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(`
117
- `);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
118
- \x1B[2K`);output.append(`\x1B[${extraLines}A`)}if(output.append("\x1B[?2026l"),process.env.DRAHT_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}`,`finalCursorRow: ${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(`
119
- `);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){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),import_bash=__toESM(require_bash(),1),import_c=__toESM(require_c(),1),import_cpp=__toESM(require_cpp(),1),import_csharp=__toESM(require_csharp(),1),import_dart=__toESM(require_dart(),1),import_go=__toESM(require_go(),1),import_groovy=__toESM(require_groovy(),1),import_java=__toESM(require_java(),1),import_javascript=__toESM(require_javascript(),1),import_json=__toESM(require_json(),1),import_kotlin=__toESM(require_kotlin(),1),import_lua=__toESM(require_lua(),1),import_nix=__toESM(require_nix(),1),import_perl=__toESM(require_perl(),1),import_php=__toESM(require_php(),1),import_python=__toESM(require_python(),1),import_ruby=__toESM(require_ruby(),1),import_rust=__toESM(require_rust(),1),import_scala=__toESM(require_scala(),1),import_swift=__toESM(require_swift(),1),import_typescript=__toESM(require_typescript(),1);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(html2,index){let semicolonIndex=html2.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html2.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python:import_python.default,java:import_java.default,go:import_go.default,javascript:import_javascript.default,json:import_json.default,cpp:import_cpp.default,typescript:import_typescript.default,php:import_php.default,ruby:import_ruby.default,c:import_c.default,csharp:import_csharp.default,nix:import_nix.default,bash:import_bash.default,rust:import_rust.default,scala:import_scala.default,kotlin:import_kotlin.default,swift:import_swift.default,dart:import_dart.default,groovy:import_groovy.default,perl:import_perl.default,lua:import_lua.default};for(let[name,language]of Object.entries(eagerLanguages))import_core.default.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./lib-XOG5PI3Y.js").then(()=>resolve(),()=>{resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag2){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag2),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!==-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(html2,index){if(!html2.startsWith("<span",index))return!1;let nextChar=html2[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
120
- `||nextChar==="\r"}function renderHighlightedHtml(html2,theme2={}){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?textBuffer.split(`
121
- `).map(line=>line&&formatter(line)).join(`
122
- `):textBuffer,textBuffer=""},index=0;for(;index<html2.length;){if(isSpanOpenTagStart(html2,index)){let tagEndIndex=html2.indexOf(">",index+5);if(tagEndIndex!==-1){flushText();let tag2=html2.slice(index,tagEndIndex+1),scope=getScopeFromSpanTag(tag2);scopes.push(scope),index=tagEndIndex+1;continue}}if(html2.startsWith(SPAN_CLOSE,index)){flushText(),scopes.length>0&&scopes.pop(),index+=SPAN_CLOSE.length;continue}if(html2[index]==="&"){let decoded=decodeHtmlEntityAt(html2,index);if(decoded){textBuffer+=decoded.text,index+=decoded.length;continue}}textBuffer+=html2[index],index++}return flushText(),output}function highlight(code,options2={}){let html2=options2.language?import_core.default.highlight(code,{language:options2.language,ignoreIllegals:options2.ignoreIllegals}).value:import_core.default.highlightAuto(code,options2.languageSubset).value;return renderHighlightedHtml(html2,options2.theme)}function supportsLanguage(name){return import_core.default.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:{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:"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",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:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},TOKEN_SLOTS={syntaxString:2,syntaxNumber:5,searchMatchBg:3},LEVELS={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},TOOL_PANELS=["toolPendingBg","toolSuccessBg","toolErrorBg"],MESSAGE_PANELS=["userMessageBg","customMessageBg"],PANELS=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],THINKING=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],THINKING_LEVELS=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],each=(tokens,on,level)=>tokens.map(token=>({token,on,level})),RULES=[...each(PANELS,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:TOOL_PANELS,level:"textOnPanel"},...each(["accent","success","error","warning"],["background","selectedBg",...TOOL_PANELS],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...TOOL_PANELS],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...TOOL_PANELS],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","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:"scrollbarThumb",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)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){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.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=x=>Math.exp(-((x-.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<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?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??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<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(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)){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}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(source,family,lightness,saturation){let anchor=saturationCurve(family,source.l),falloff=anchor>0?Math.min(1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source.h,source.s*falloff*saturation,lightness),cap=source.chroma*falloff*saturation,{l,c:c2}=colorToOklch(color);return c2<=cap?color:colorToRgb(oklchColor(l,cap,source.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,s,l}=okhslOf(color),at=lightness=>okhslColor(h,s,lightness),extreme=lighter?1:0;if(!meets(at(extreme)))return at(extreme);let[low,high]=[l,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at(middle))?high=middle:low=middle}return at(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&&!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:"Primary 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:"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:"background",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 message 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 execution 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 content"},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 lines 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 literals"},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:{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 mode"}});var 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],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(`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")},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!==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,options2={}){this.name=options2.name,this.sourcePath=options2.sourcePath,this.sourceInfo=options2.sourceInfo,this.mode=mode,this.dimTokens=new Set(options2.dim);let{fgColors:foregrounds,bgColors:backgrounds}=splitThemeColors(withThemeTokenFallbacks({...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))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=options2.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.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,options2){let{fg,bg}=options2;return typeof fg=="string"&&this.dimTokens.has(fg)&&(options2={...options2,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),options2)}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}\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[2m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str2=>this.fg("thinkingOff",str2);case"minimal":return str2=>this.fg("thinkingMinimal",str2);case"low":return str2=>this.fg("thinkingLow",str2);case"medium":return str2=>this.fg("thinkingMedium",str2);case"high":return str2=>this.fg("thinkingHigh",str2);case"xhigh":return str2=>this.fg("thinkingXhigh",str2);case"max":return str2=>this.fg("thinkingMax",str2);default:return str2=>this.fg("thinkingOff",str2)}}getBashModeBorderColor(){return str2=>this.fg("bashMode",str2)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(darkPath,"utf-8"))),light:JSON.parse(stripBom(fs3.readFileSync(lightPath,"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))};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=[];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 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){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(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(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(),{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,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(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?terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("@draht/coding-agent:theme"),THEME_KEY_OLD=Symbol.for("@draht/coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[prop]}});function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_OLD]=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){let name=themeName??getTerminalTheme();currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{let fallback=getTerminalTheme();currentThemeName=fallback,setGlobalTheme(loadTheme(fallback))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){let fallback=getTerminalTheme();return currentThemeName=fallback,setGlobalTheme(loadTheme(fallback)),{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(),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&&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(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};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.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.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(`
123
- `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
124
- `)}catch{return code.split(`
125
- `)}}function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();return ext?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[ext]:void 0}function getMarkdownTheme(){return{heading:text=>theme.fg("mdHeading",text),link:text=>theme.fg("mdLink",text),linkUrl:text=>theme.fg("mdLinkUrl",text),code:text=>theme.fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.fg("mdCodeBlockBorder",text),quote:text=>theme.fg("mdQuote",text),quoteBorder:text=>theme.fg("mdQuoteBorder",text),hr:text=>theme.fg("mdHr",text),listBullet:text=>theme.fg("mdListBullet",text),bold:text=>theme.bold(text),italic:text=>theme.italic(text),underline:text=>theme.underline(text),strikethrough:text=>theme.strikethrough(text),highlightCode:(code,lang)=>{let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
126
- `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
127
- `)}catch{return code.split(`
128
- `).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,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,options2){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options2.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options2={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options2)).join("+")).join("/")}function formatKeys(keys,options2={}){return keys.length===0?"":formatKeyText(keys.join("/"),options2)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}var ARROW_GLYPHS={up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192"};function combinedKeyText(keybindings){let perBinding=keybindings.map(id=>getKeybindings().getKeys(id));return perBinding.every(keys=>keys.length===1&&keys[0]in ARROW_GLYPHS)?perBinding.map(keys=>ARROW_GLYPHS[keys[0]]).join(""):keybindings.map(id=>keyText(id)).join("/")}function combinedKeyHint(keybindings,description){return theme.fg("dim",combinedKeyText(keybindings))+theme.fg("muted",` ${description}`)}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}`)}function isValidUsage(value){if(typeof value!="object"||value===null)return!1;let u=value;if(![u.input,u.output,u.cacheRead,u.cacheWrite,u.totalTokens].every(n=>typeof n=="number"&&Number.isFinite(n))||typeof u.cost!="object"||u.cost===null)return!1;let cost=u.cost;return[cost.input,cost.output,cost.cacheRead,cost.cacheWrite,cost.total].every(n=>typeof n=="number"&&Number.isFinite(n))}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
129
- `);return content.endsWith(`
130
- `)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options2={}){let maxLines=options2.maxLines??2e3,maxBytes=options2.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
131
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options2={}){let maxLines=options2.maxLines??2e3,maxBytes=options2.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
132
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str2,maxBytes){let buf=Buffer.from(str2,"utf-8");if(buf.length<=maxBytes)return str2;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}function truncateMiddle(content,maxBytes){let buf=Buffer.from(content,"utf-8"),totalLines=splitLinesForCounting(content).length;if(buf.length<=maxBytes)return{content,truncated:!1,removedChars:0,totalBytes:buf.length,totalLines};let isBoundary=index=>index>=buf.length||(buf[index]&192)!==128,headEnd=Math.floor(maxBytes/2);for(;headEnd>0&&!isBoundary(headEnd);)headEnd--;let tailStart=buf.length-(maxBytes-Math.floor(maxBytes/2));for(;tailStart<buf.length&&!isBoundary(tailStart);)tailStart++;let head=buf.subarray(0,headEnd).toString("utf-8"),tail=buf.subarray(tailStart).toString("utf-8"),removedChars=Array.from(buf.subarray(headEnd,tailStart).toString("utf-8")).length;return{content:`${head}\u2026${removedChars} chars truncated\u2026${tail}`,truncated:!0,removedChars,totalBytes:buf.length,totalLines}}import*as os2 from"node:os";import{pathToFileURL as pathToFileURL2}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path5){if(typeof path5!="string")return"";let home=os2.homedir();return path5.startsWith(home)?`~${path5.slice(home.length)}`:path5}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL2(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c2=>c2.type==="text"),imageBlocks=result.content.filter(c2=>c2.type==="image"),output=textBlocks.map(c2=>sanitizeBinaryOutput(stripAnsi(c2.text||"")).replace(/\r/g,"")).join(`
133
- `),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
134
- `);output=output?`${output}
135
- ${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme2,expanded){let header=theme2.fg("toolTitle",theme2.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text).replace(/\r/g,"").split(`
136
- `).join(`
137
- `)}`});return`${header}
138
- ${theme2.fg("muted",lines.join(`
139
- `))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme2.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),!isPartial&&context.durationMs!==void 0)return`Took ${formatToolDuration(context.durationMs)}`;if(state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme2){return theme2.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme2,cwd,options2){if(rawPath===null)return invalidArgText(theme2);let value=rawPath||options2?.emptyFallback;return value?linkPath(theme2.fg("accent",shortenPath(value)),value,cwd):theme2.fg("toolOutput","...")}import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import{join as join7}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join7(tmpdir2(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path5=createOutputFilePath(prefix,extension);return await writeFile(path5,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path5}function createOutputFileStream(prefix,extension){let path5=createOutputFilePath(prefix,extension);return{path:path5,stream:createWriteStream(path5,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options2){this.options=options2}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){return text.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(term=>term.length>0&&!STOP_WORDS.has(term)).map(stem)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,parts){if(isObject(schema)){if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,parts);schemaText(schema.items,parts);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,parts)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.name,tool.name.replaceAll("_"," "),tool.description];return schemaText(tool.parameters,parts),namespace&&parts.push(namespace.name,namespace.description??"",namespace.instructions??""),{name:tool.name,text:parts.filter(part=>part.trim()).join(" ")}}var Bm25Ranker=class{k1;b;constructor(options2={}){this.k1=options2.k1??1.2,this.b=options2.b??.75}rank(query,documents,limit){let queryTerms=[...new Set(tokenize(query))];if(queryTerms.length===0||documents.length===0||limit<=0)return[];let termCounts=documents.map(document=>{let counts=new Map;for(let term of tokenize(document.text))counts.set(term,(counts.get(term)??0)+1);return counts}),lengths=termCounts.map(counts=>[...counts.values()].reduce((sum,count)=>sum+count,0)),averageLength=lengths.reduce((sum,length)=>sum+length,0)/documents.length||1,idf=new Map(queryTerms.map(term=>{let frequency=termCounts.filter(counts=>counts.has(term)).length;return[term,Math.log(1+(documents.length-frequency+.5)/(frequency+.5))]})),matches=[];return documents.forEach((document,index)=>{let score=0;for(let term of queryTerms){let count=termCounts[index].get(term);if(!count)continue;let norm=this.k1*(1-this.b+this.b*lengths[index]/averageLength);score+=(idf.get(term)??0)*(count*(this.k1+1)/(count+norm))}score>0&&matches.push({name:document.name,score})}),matches.sort((a,b)=>b.score-a.score).slice(0,limit)}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
140
-
141
- Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
142
-
143
- Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options2={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options2.tools?searchAndLoad(options2.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
144
- ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
145
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join8}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-ZVQ7ITER.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
146
- ${theme2.fg("error",call.error.split(`
147
- `).join(`
148
- `))}`),line}var codemodeRenderers={renderCall(args,theme2,context){startToolTimer(context);let code=str(args?.code),title=theme2.fg("toolTitle",theme2.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme2.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
149
- `);component.addChild(context.expanded?new Text(highlighted,0,0):new VisualLinePreview({text:highlighted,maxVisualLines:CODE_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme2,hidden,"lines")}))}return component},renderResult(result,options2,theme2,context){let timerText=toolTimerText(context,options2.isPartial),component=context.lastComponent??new Container;component.clear();let calls=result.details?.calls??[];if(calls.length>0){let shown=options2.expanded?calls:calls.slice(-CALL_PREVIEW_COUNT),lines=shown.map(call=>formatCall(call,theme2,options2.expanded));shown.length<calls.length&&lines.unshift(`${theme2.fg("muted",`... (${calls.length-shown.length} earlier calls,`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`);let priced=calls.filter(call=>call.cost);if(priced.length>1){let total=priced.reduce((sum,call)=>sum+(call.cost??0),0);lines.push(theme2.fg("muted",`Model calls: ${formatCost(total)}`))}component.addChild(new Spacer(1)),component.addChild(new Text(lines.join(`
150
- `),0,0))}let[first,...rest]=result.content,hasHeader=first?.type==="text"&&SCRIPT_HEADER.test(first.text),output=options2.isPartial?"":getTextOutput({...result,content:hasHeader?rest:result.content},context.showImages).trim();if(output){let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
151
- `).map(line=>theme2.fg(color,line)).join(`
152
- `);if(component.addChild(new Spacer(1)),options2.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme2,hidden,"lines")}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme2.fg("muted",`Full output: ${fullOutputPath}`),0,0))}}return timerText&&(component.addChild(new Spacer(1)),component.addChild(new Text(theme2.fg("muted",timerText),0,0))),component}};var CODEMODE_TOOL_NAME="codemode",CODEMODE_STORE_ENTRY_TYPE="codemode-store",TEXT_OUTPUT_SCHEMA={type:"string"},codemodeSchema=typebox_exports.Object({code:typebox_exports.String({description:"Raw JavaScript source."})}),codemodeToolSystemPromptContribution={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},CODEMODE_DOCS_PATH=join8(getDocsPath(),"codemode.md"),DESCRIPTION_INTRO='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function describeGlobals(models){let lines=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return models&&lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`),lines.join(`
153
- `)}var DEFAULT_CODEMODE_INLINE_BUDGET=SETTINGS_DEFAULTS.codemode.inlineBudget,CHARS_PER_TOKEN=4;function toCodemodeDeclaration(tool,guidelines=[]){let bullets=guidelines.flatMap(guideline=>guideline.trim()?[`- ${guideline.trim()}`]:[]);return{name:tool.name,description:bullets.length>0?`${tool.description.trim()}
154
-
155
- ${bullets.join(`
156
- `)}`:tool.description,inputSchema:tool.parameters,outputSchema:tool.outputSchema??TEXT_OUTPUT_SCHEMA}}function getCodemodeCallableTools(tools){return tools.filter(tool=>tool.name!==CODEMODE_TOOL_NAME)}function renderToolSection(declaration){let id=toCodemodeIdentifier(declaration.name);return`${id===declaration.name?`### \`${id}\``:`### \`${id}\` (\`${declaration.name}\`)`}
157
- ${renderToolSample(declaration).trim()}`}function selectCatalog(groups,budget){if(budget===void 0)return new Set(groups.flatMap(group=>group.entries.map(entry=>entry.name)));let queues=groups.map(group=>[...group.entries].sort((a,b)=>a.cost-b.cost)),shown=new Set,remaining=budget,active=queues.filter(queue=>queue.length>0);for(;active.length>0;)active=active.filter(queue=>{let next=queue[0];return next.cost>remaining?!1:(remaining-=next.cost,shown.add(next.name),queue.shift(),queue.length>0)});return shown}function createCodemodeDescription(tools,options2={}){let declarations=getCodemodeCallableTools(tools).filter(tool=>!options2.deferred?.has(tool.name)).map(tool=>toCodemodeDeclaration(tool,options2.guidelines?.get(tool.name))),groups=new Map([["",{namespace:void 0,entries:[]}]]);for(let declaration of declarations){let namespace=options2.namespaces?.get(declaration.name),key=namespace?`ns:${namespace.name}`:"",group=groups.get(key)??{namespace,entries:[]};groups.set(key,group);let section=renderToolSection(declaration);group.entries.push({name:declaration.name,section,cost:Math.ceil(section.length/CHARS_PER_TOKEN)})}let ordered=[...groups.values()].sort((a,b)=>a.namespace===void 0?-1:b.namespace===void 0?1:a.namespace.name.localeCompare(b.namespace.name)),shown=selectCatalog(ordered,options2.inlineBudget),sections=[DESCRIPTION_INTRO,describeGlobals(options2.models===!0)];if(declarations.length===0)return sections.join(`
158
-
159
- `);let toolSections=["Nested tools:"];for(let{namespace,entries}of ordered){let visible=entries.filter(entry=>shown.has(entry.name));if(namespace){let listing=visible.length===entries.length?"":visible.length===0?" (tools not listed)":" (some tools not listed)",description=namespace.description?.trim();toolSections.push(`## ${namespace.name}${listing}${description?`
160
- ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}return sections.push(toolSections.join(`
161
-
162
- `)),sections.join(`
163
-
164
- `)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let nested=depth>0?describeFields(field,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(schema){let type=renderToolOutputType(schema);return type==="string"?"a string":`\`${describeFields(schema,1)??type.replace(/\s+/g," ")}\``}function describeScriptCall(tool){return`${tool.description.trim()}
165
-
166
- Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options2){let mode=options2.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options2.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options2.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options2={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options2.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options2),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options2),...codemodeRenderers}}export{guard_exports,emit_exports,globals_exports,guard_default,Get,settings_exports,Clone,IsSchema,_Array_,IsArray3 as IsArray,ArrayOptions,IsConstructor3 as IsConstructor,IsFunction3 as IsFunction,Ref,IsRef,IsNever,IsOptional,_Object_,IsObject3 as IsObject,Unknown,IsCyclic,arguments_exports,IsEnum,Intersect,IsIntersect,environment_exports,Unreachable,hash_exports,Get2,IsCodec,IsRefine,IsBigInt3 as IsBigInt,IsBoolean4 as IsBoolean,IsInteger3 as IsInteger,Literal,IsLiteralBigInt,IsLiteralBoolean,IsLiteralNumber,IsLiteralString,IsLiteral,IsNull3 as IsNull,IsNumber4 as IsNumber,IsSymbol3 as IsSymbol,String2 as String,IsString4 as IsString,Union,IsUnion,TemplateLiteralDecode,Tuple,IsTuple,Flatten,Record,RecordPattern,RecordKey,RecordValue,IsRecord,IsUndefined3 as IsUndefined,IsVoid,IsTemplateLiteral,With2 as With,Instantiate,Evaluate2 as Evaluate,Priority,typebox_exports,build_exports,Marked,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,parseColor,mixColors,foregroundAnsi,Key,isKeyRelease,isKeyRepeat,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,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,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,combinedKeyHint,keyDisplayText,keyHint,rawKeyHint,isValidUsage,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,splitIncompleteAnsiSuffix,stripAnsi,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,writeOutputFile,createOutputFileStream,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};