pi-namespace-patch 1.0.0-namespace.2 → 1.0.2-namespace.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 (185) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +3 -3
  3. package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-MVG2FL56.js} +3 -3
  4. package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  6. package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
  7. package/dist/bundle/chunks/{chunk-2KTBZM5G.js → chunk-6FX7UEPL.js} +5 -5
  8. package/dist/bundle/chunks/{chunk-2VNGUWBO.js → chunk-BYB6ZAAQ.js} +1 -1
  9. package/dist/bundle/chunks/chunk-DN3QEIXS.js +2 -0
  10. package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
  11. package/dist/bundle/chunks/{chunk-3LH3ZQKY.js → chunk-G7EDXK4D.js} +1 -1
  12. package/dist/bundle/chunks/chunk-IKZJX7ZT.js +2 -0
  13. package/dist/bundle/chunks/{chunk-4N5K4RKC.js → chunk-OLBCNJCL.js} +31 -32
  14. package/dist/bundle/chunks/{chunk-PRD6WYBT.js → chunk-OYBSLV7Y.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-IBCPYVFK.js → chunk-PDFMCAOZ.js} +4 -4
  16. package/dist/bundle/chunks/{chunk-LTXEMVMA.js → chunk-SYF2TF6W.js} +2 -2
  17. package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
  18. package/dist/bundle/chunks/{chunk-KDN6RCEQ.js → chunk-ZSI3BL5Q.js} +2 -2
  19. package/dist/bundle/chunks/{cli-QOMC26IJ.js → cli-KILDDGW3.js} +2 -2
  20. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
  21. package/dist/bundle/chunks/codemode-worker.js +24 -3
  22. package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
  23. package/dist/bundle/chunks/{execute-GVRSEGHL.js → execute-RYVK27GT.js} +25 -4
  24. package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js} +1 -1
  25. package/dist/bundle/chunks/{google-vertex-MXCOSOY3.js → google-vertex-VKWZQ3AY.js} +1 -1
  26. package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js} +1 -1
  27. package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
  28. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  29. package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js} +1 -1
  30. package/dist/bundle/chunks/openai-completions-GWHGMQ3T.js +7 -0
  31. package/dist/bundle/chunks/openai-responses-EZ7FJ2KL.js +3 -0
  32. package/dist/bundle/chunks/{runtime-2SO2JDWM.js → runtime-D5I2NTIF.js} +1 -1
  33. package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +2 -0
  34. package/dist/bundle/cli-runtime.js +1 -1
  35. package/dist/bundle/index.js +1 -1
  36. package/dist/bundle/rpc-entry.js +1 -1
  37. package/dist/cli/args.d.ts.map +1 -1
  38. package/dist/cli/args.js +4 -1
  39. package/dist/cli/args.js.map +1 -1
  40. package/dist/config.d.ts.map +1 -1
  41. package/dist/config.js +3 -0
  42. package/dist/config.js.map +1 -1
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +1 -1
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/export-html/tool-renderer.d.ts +3 -3
  47. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  48. package/dist/core/export-html/tool-renderer.js +3 -3
  49. package/dist/core/export-html/tool-renderer.js.map +1 -1
  50. package/dist/core/extensions/index.d.ts +1 -1
  51. package/dist/core/extensions/index.d.ts.map +1 -1
  52. package/dist/core/extensions/index.js.map +1 -1
  53. package/dist/core/extensions/loader.d.ts.map +1 -1
  54. package/dist/core/extensions/loader.js +5 -0
  55. package/dist/core/extensions/loader.js.map +1 -1
  56. package/dist/core/extensions/runner.d.ts +3 -1
  57. package/dist/core/extensions/runner.d.ts.map +1 -1
  58. package/dist/core/extensions/runner.js +6 -0
  59. package/dist/core/extensions/runner.js.map +1 -1
  60. package/dist/core/extensions/types.d.ts +9 -0
  61. package/dist/core/extensions/types.d.ts.map +1 -1
  62. package/dist/core/extensions/types.js.map +1 -1
  63. package/dist/core/mcp-servers.d.ts +6 -0
  64. package/dist/core/mcp-servers.d.ts.map +1 -1
  65. package/dist/core/mcp-servers.js +11 -0
  66. package/dist/core/mcp-servers.js.map +1 -1
  67. package/dist/core/model-config.d.ts +36 -0
  68. package/dist/core/model-config.d.ts.map +1 -1
  69. package/dist/core/model-config.js +14 -2
  70. package/dist/core/model-config.js.map +1 -1
  71. package/dist/core/model-resolver.js +1 -1
  72. package/dist/core/model-resolver.js.map +1 -1
  73. package/dist/core/provider-composer.d.ts +2 -1
  74. package/dist/core/provider-composer.d.ts.map +1 -1
  75. package/dist/core/provider-composer.js +13 -0
  76. package/dist/core/provider-composer.js.map +1 -1
  77. package/dist/core/tools/renderers/index.d.ts +2 -2
  78. package/dist/core/tools/renderers/index.d.ts.map +1 -1
  79. package/dist/core/tools/renderers/index.js.map +1 -1
  80. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  81. package/dist/extensions/mcp/cli.js +3 -0
  82. package/dist/extensions/mcp/cli.js.map +1 -1
  83. package/dist/extensions/mcp/config.d.ts +15 -3
  84. package/dist/extensions/mcp/config.d.ts.map +1 -1
  85. package/dist/extensions/mcp/config.js +46 -10
  86. package/dist/extensions/mcp/config.js.map +1 -1
  87. package/dist/extensions/mcp/index.d.ts +4 -1
  88. package/dist/extensions/mcp/index.d.ts.map +1 -1
  89. package/dist/extensions/mcp/index.js +80 -45
  90. package/dist/extensions/mcp/index.js.map +1 -1
  91. package/dist/extensions/mcp/oauth.d.ts +4 -1
  92. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  93. package/dist/extensions/mcp/oauth.js +54 -10
  94. package/dist/extensions/mcp/oauth.js.map +1 -1
  95. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  96. package/dist/extensions/mcp/runtime.js +1 -0
  97. package/dist/extensions/mcp/runtime.js.map +1 -1
  98. package/dist/extensions/mcp/tools.d.ts +3 -1
  99. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  100. package/dist/extensions/mcp/tools.js +19 -13
  101. package/dist/extensions/mcp/tools.js.map +1 -1
  102. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  103. package/dist/extensions/mcp/ui.js +8 -4
  104. package/dist/extensions/mcp/ui.js.map +1 -1
  105. package/dist/index.d.ts +1 -1
  106. package/dist/index.d.ts.map +1 -1
  107. package/dist/index.js.map +1 -1
  108. package/dist/modes/interactive/components/armin.d.ts +3 -0
  109. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/armin.js +7 -5
  111. package/dist/modes/interactive/components/armin.js.map +1 -1
  112. package/dist/modes/interactive/components/auth-url.d.ts +14 -0
  113. package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
  114. package/dist/modes/interactive/components/auth-url.js +37 -0
  115. package/dist/modes/interactive/components/auth-url.js.map +1 -0
  116. package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
  117. package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
  118. package/dist/modes/interactive/components/{pi-logo-animation.js → easter-egg-3d.js} +127 -74
  119. package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
  120. package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
  121. package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
  122. package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
  123. package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
  124. package/dist/modes/interactive/components/index.d.ts +0 -1
  125. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  126. package/dist/modes/interactive/components/index.js +0 -1
  127. package/dist/modes/interactive/components/index.js.map +1 -1
  128. package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
  129. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/login-dialog.js +11 -5
  131. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  132. package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
  133. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/tool-execution.js +22 -45
  135. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  136. package/dist/modes/interactive/interactive-mode.d.ts +2 -2
  137. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  138. package/dist/modes/interactive/interactive-mode.js +15 -17
  139. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  140. package/dist/package-manager-cli.d.ts.map +1 -1
  141. package/dist/package-manager-cli.js +12 -0
  142. package/dist/package-manager-cli.js.map +1 -1
  143. package/dist/utils/image-convert.d.ts +12 -0
  144. package/dist/utils/image-convert.d.ts.map +1 -1
  145. package/dist/utils/image-convert.js +45 -6
  146. package/dist/utils/image-convert.js.map +1 -1
  147. package/docs/cli.md +2 -0
  148. package/docs/codemode.md +1 -1
  149. package/docs/extensions.md +4 -0
  150. package/docs/keybindings.md +1 -1
  151. package/docs/mcp.md +23 -1
  152. package/docs/models.md +28 -2
  153. package/docs/quickstart.md +16 -2
  154. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  155. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  156. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  157. package/examples/extensions/gondolin/package-lock.json +2 -2
  158. package/examples/extensions/gondolin/package.json +1 -1
  159. package/examples/extensions/sandbox/package-lock.json +2 -2
  160. package/examples/extensions/sandbox/package.json +1 -1
  161. package/examples/extensions/with-deps/package-lock.json +2 -2
  162. package/examples/extensions/with-deps/package.json +1 -1
  163. package/package.json +13 -14
  164. package/dist/bundle/chunks/azure-openai-responses-AFMVM6NP.js +0 -2
  165. package/dist/bundle/chunks/chunk-6D7LHLKG.js +0 -2
  166. package/dist/bundle/chunks/chunk-7FH3BDRG.js +0 -82
  167. package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
  168. package/dist/bundle/chunks/chunk-MJOHEBV7.js +0 -2
  169. package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
  170. package/dist/bundle/chunks/openai-completions-JXDDPZ23.js +0 -7
  171. package/dist/bundle/chunks/openai-responses-CQDDLDQF.js +0 -3
  172. package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +0 -2
  173. package/dist/bundle/chunks/virtual-modules-3THEGRQQ.js +0 -2
  174. package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
  175. package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
  176. package/dist/modes/interactive/components/daxnuts.js +0 -140
  177. package/dist/modes/interactive/components/daxnuts.js.map +0 -1
  178. package/dist/modes/interactive/components/pi-logo-animation.d.ts +0 -68
  179. package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +0 -1
  180. package/dist/modes/interactive/components/pi-logo-animation.js.map +0 -1
  181. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +0 -7
  182. package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +0 -1
  183. package/dist/modes/interactive/components/pi-logo-animation.lazy.js +0 -12
  184. package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +0 -1
  185. package/npm-shrinkwrap.json +0 -1952
@@ -3,7 +3,7 @@ import{require_bash,require_c,require_core,require_cpp,require_csharp,require_da
3
3
  `:!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===`
4
4
  `||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)}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)return formatParsedKey(kitty.codepoint,kitty.modifier,kitty.baseLayoutKey);let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys)return formatParsedKey(modifyOtherKeys.codepoint,modifyOtherKeys.modifier);if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
5
5
  `))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===`
6
- `||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)}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+home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+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:"home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"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 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:()=>Z,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,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,isAppleTerminalSession:()=>isAppleTerminalSession,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,renderImage:()=>renderImage,renderLatex:()=>renderLatex,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var R=A();function j(l3){R=l3}var z={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function k(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Oe=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={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,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,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,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},Te=/^(?:[ \t]*(?:\n|$))+/,we=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,q=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,U=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Se=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),K=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,_e=/^[^\n]+/,W=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$e=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",W).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Le=k(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,U).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|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",X=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ee=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\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",X).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=l3=>k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),ze=le(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Me=le(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ae=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Me).getRegex(),J={blockquote:Ae,code:we,def:$e,fences:ye,heading:Pe,hr:q,html:Ee,lheading:ae,list:Le,newline:Te,paragraph:ze,table:z,text:_e},se=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),Ie={...J,lheading:Se,table:se,paragraph:k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex()},Ce={...J,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",X).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:z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(K).replace("hr",q).replace("heading",` *#{1,6} *[^
6
+ `||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)}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+home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+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:"home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"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 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:()=>Z,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,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,isAppleTerminalSession:()=>isAppleTerminalSession,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,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 A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var R=A();function j(l3){R=l3}var z={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function k(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Oe=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={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,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,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,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},Te=/^(?:[ \t]*(?:\n|$))+/,we=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,q=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,U=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Se=k(oe).replace(/bull/g,U).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),K=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,_e=/^[^\n]+/,W=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$e=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",W).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Le=k(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,U).getRegex(),Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|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",X=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ee=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\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",X).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=l3=>k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),ze=le(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Me=le(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ae=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Me).getRegex(),J={blockquote:Ae,code:we,def:$e,fences:ye,heading:Pe,hr:q,html:Ee,lheading:ae,list:Le,newline:Te,paragraph:ze,table:z,text:_e},se=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex(),Ie={...J,lheading:Se,table:se,paragraph:k(K).replace("hr",q).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Q).getRegex()},Ce={...J,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",X).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:z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(K).replace("hr",q).replace("heading",` *#{1,6} *[^
7
7
  ]`).replace("lheading",ae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Be=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,De=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ue=/^( {2,}|\\)\n(?!\s*$)/,qe=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_=/[\p{P}\p{S}]/u,C=/[\s\p{P}\p{S}]/u,v=/[^\s\p{P}\p{S}]/u,ve=k(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,C).getRegex(),He=/[\p{Pi}\p{Ps}"']/u,pe=/(?!~)[\p{P}\p{S}]/u,Ze=/(?!~)[\s\p{P}\p{S}]/u,Ge=/(?:[^\s\p{P}\p{S}]|~)/u,Qe=k(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Oe?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ne=k(ce,"u").replace(/punct/g,_).getRegex(),je=k(ce,"u").replace(/punct/g,pe).getRegex(),Fe=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Ue=k(Fe,"u").replace(/openQuote/g,He).replace(/punct/g,_).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ke=k(he,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),We=k(he,"gu").replace(/notPunctSpace/g,Ge).replace(/punctSpace/g,Ze).replace(/punct/g,pe).getRegex(),Xe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Je=k(Xe,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),Ve=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),Ye="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",et=k(Ye,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),tt=k(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_).getRegex(),nt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",rt=k(nt,"gu").replace(/notPunctSpace/g,v).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),st=k(/\\(punct)/,"gu").replace(/punct/g,_).getRegex(),it=k(/^<(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(),ot=k(X).replace("(?:-->|$)","-->").getRegex(),at=k("^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",ot).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),G=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,lt=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",G).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=k(/^!?\[(label)\]\[(ref)\]/).replace("label",G).replace("ref",W).getRegex(),de=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",W).getRegex(),ut=k("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",de).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V={_backpedal:z,anyPunctuation:st,autolink:it,blockSkip:Qe,br:ue,code:De,del:z,delLDelim:z,delRDelim:z,emStrongLDelim:Ne,emStrongRDelimAst:Ke,emStrongRDelimUnd:Ve,escape:Be,link:lt,nolink:de,punctuation:ve,reflink:ke,reflinkSearch:ut,tag:at,text:qe,url:z},pt={...V,emStrongLDelim:Ue,emStrongRDelimAst:Je,emStrongRDelimUnd:et,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",G).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",G).getRegex()},F={...V,emStrongRDelimAst:We,emStrongLDelim:je,delLDelim:tt,delRDelim:rt,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ie).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\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ie).getRegex()},ct={...F,br:k(ue).replace("{2,}","*").getRegex(),text:k(F.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},H={normal:J,gfm:Ie,pedantic:Ce},B={normal:V,gfm:F,breaks:ct,pedantic:pt},ht={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ge=l3=>ht[l3];function T(l3,e){if(e){if(m.escapeTest.test(l3))return l3.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l3))return l3.replace(m.escapeReplaceNoEncode,ge);return l3}function Y(l3){try{l3=encodeURI(l3).replace(m.percentDecode,"%")}catch{return null}return l3}function ee(l3,e){let t=l3.replace(m.findPipe,(r,i,o)=>{let u=!1,a=i;for(;--a>=0&&o[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,"|");return n}function $(l3,e,t){let n=l3.length;if(n===0)return"";let s=0;for(;s<n;){let r=l3.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l3.slice(0,n-s)}function te(l3){let e=l3.split(`
8
8
  `),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
9
9
  `)}function fe(l3,e){if(l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function me(l3,e=0){let t=e,n="";for(let s of l3)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function xe(l3,e,t,n,s){let r=e.href,i=e.title||null,o=l3[1].replace(s.other.outputLinkReplace,"$1"),u=l3[0].charAt(0)==="!";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c2=n.inlineTokens(o),h=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(h){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:t,href:r,title:i,text:o,tokens:c2}}function kt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
@@ -68,7 +68,7 @@ ${e}</tr>
68
68
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
69
69
  `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${T(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Y(e);if(r===null)return s;e=r;let i='<a href="'+e+'"';return t&&(i+=' title="'+T(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Y(e);if(r===null)return T(n);e=r;let i=`<img src="${e}" alt="${T(n)}"`;return t&&(i+=` title="${T(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:T(e.text)}},L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},b=class l2{options;renderer;textRenderer;constructor(e){this.options=e||R,this.options.renderer=this.options.renderer||new P,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let i=s,o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(i.type)){t+=o||"";continue}}let r=s;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let i='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=o||"";continue}}let i=r;switch(i.type){case"escape":{n+=t.text(i);break}case"html":{n+=t.html(i);break}case"link":{n+=t.link(i);break}case"image":{n+=t.image(i);break}case"checkbox":{n+=t.checkbox(i);break}case"strong":{n+=t.strong(i);break}case"em":{n+=t.em(i);break}case"codespan":{n+=t.codespan(i);break}case"br":{n+=t.br(i);break}case"del":{n+=t.del(i);break}case"text":{n+=t.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}},S=class{options;block;constructor(e){this.options=e||R}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}},Z=class{defaults=A();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=P;TextRenderer=L;Lexer=x;Tokenizer=y;Hooks=S;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let u=r.renderer.apply(this,o);return u===!1&&(u=i.apply(this,o)),u}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new P(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,u=n.renderer[o],a=r[o];r[o]=(...p)=>{let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new y(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,u=n.tokenizer[o],a=r[o];r[o]=(...p)=>{let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new S;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,u=n.hooks[o],a=r[o];S.passThroughHooks.has(i)?r[o]=p=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await u.call(r,p);return a.call(r,h)})();let c2=u.call(r,p);return a.call(r,c2)}:r[o]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await u.apply(r,p);return h===!1&&(h=await a.apply(r,p)),h})();let c2=u.apply(r,p);return c2===!1&&(c2=a.apply(r,p)),c2}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let u=[];return u.push(i.call(this,o)),r&&(u=u.concat(r.call(this,o))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let u=i.hooks?await i.hooks.preprocess(n):n,p=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,i),c2=i.hooks?await i.hooks.processAllTokens(p):p;i.walkTokens&&await Promise.all(this.walkTokens(c2,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(c2,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let c2=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(c2=i.hooks.postprocess(c2)),c2}catch(u){return o(u)}}}onError(e,t){return n=>{if(n.message+=`
70
70
  Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+T(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},M=new Z;function f(l3,e){return M.parse(l3,e)}f.options=f.setOptions=function(l3){return M.setOptions(l3),f.defaults=M.defaults,j(f.defaults),f};f.getDefaults=A;f.defaults=R;function dt(...l3){return M.use(...l3),f.defaults=M.defaults,j(f.defaults),f}f.use=dt;f.walkTokens=function(l3,e){return M.walkTokens(l3,e)};f.parseInline=M.parseInline;f.Parser=b;f.parser=b.parse;f.Renderer=P;f.TextRenderer=L;f.Lexer=x;f.lexer=x.lex;f.Tokenizer=y;f.Hooks=S;f.parse=f;var nn=f.options,rn=f.setOptions,sn=f.walkTokens,on=f.parseInline;var ln=b.parse,un=x.lex;import{spawn}from"child_process";import{readdirSync,statSync as statSync2}from"fs";import{homedir as homedir3}from"os";import{basename as basename2,dirname as dirname2,join as join3}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,b2)=>a.totalScore-b2.totalScore),results.map(r=>r.item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",segments=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment));if(segments.length===0)return normalized;let pattern=segments.join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&(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,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path5),prefix=options.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(resolve2=>{if(signal.aborted){resolve2([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,finish=results=>{resolved||(resolved=!0,signal.removeEventListener("abort",onAbort),resolve2(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(`
71
- `).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,options){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:options.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.trimStart();if(!options.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,options.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=join3(homedir3(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir3();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=join3(this.basePath,displayBase);try{if(!statSync2(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=join3(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join3(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename2(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join3(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=join3(searchDir,entry.name);isDirectory=statSync2(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=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join3(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join3(dirname2(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,b2)=>{let aIsDir=a.label.endsWith("/"),bIsDir=b2.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename2(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,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options.signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.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=basename2(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";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),b2=parseInt(normalized.slice(4,6),16);return{r,g,b:b2}}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)),b3=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b3!==void 0?{r:r2,g:g2,b:b3}: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),b2=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b2!==void 0?{r,g,b:b2}: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 homedir4}from"node:os";import{isAbsolute as isAbsolute2}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}: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.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks;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,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){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 getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(!controls)return;let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}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 getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line),metadata=getRegisteredKittyImageMetadata(line);if(!match||!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,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,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir4();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&&isAbsolute2(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},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07";function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var Container=class{children=[];mouseLayout;addChild(component){this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){for(let child of this.children)child.invalidate?.()}handleMouse(event){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("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){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,options){let entry={component,...options===void 0?{}:{options},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.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!options?.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,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(options={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}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(options,overlayHeight,termWidth,termHeight){let opt=options??{},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,b2)=>a.focusOrder-b2.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=component.render(width);maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,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}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve2=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve2,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve2(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}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 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}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,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||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,options){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options?.segment,isAtomic=options?.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();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}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 m2 of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m2[1],10);validIds.has(id)&&markers.push({start:m2.index,end:m2.index+m2[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 j2=0;j2<subChunks.length-1;j2++){let sc=subChunks[j2];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,options={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){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(`
71
+ `).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,options){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:options.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.trimStart();if(!options.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,options.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=join3(homedir3(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir3();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=join3(this.basePath,displayBase);try{if(!statSync2(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=join3(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join3(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename2(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join3(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=join3(searchDir,entry.name);isDirectory=statSync2(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=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join3(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join3(dirname2(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,b2)=>{let aIsDir=a.label.endsWith("/"),bIsDir=b2.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename2(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,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options.signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.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=basename2(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};import{performance as performance2}from"node:perf_hooks";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),b2=parseInt(normalized.slice(4,6),16);return{r,g,b:b2}}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)),b3=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b3!==void 0?{r:r2,g:g2,b:b3}: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),b2=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b2!==void 0?{r,g,b:b2}: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 homedir4}from"node:os";import{isAbsolute as isAbsolute2}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}: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.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.PI_TRUE_COLOR);return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks;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,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){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,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir4();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&&isAbsolute2(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},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07";function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var Container=class{children=[];mouseLayout;addChild(component){this.children.push(component)}removeChild(component){let index=this.children.indexOf(component);index!==-1&&this.children.splice(index,1)}clear(){this.children=[]}invalidate(){for(let child of this.children)child.invalidate?.()}handleMouse(event){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("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){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,options){let entry={component,...options===void 0?{}:{options},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.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!options?.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,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(options={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}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(options,overlayHeight,termWidth,termHeight){let opt=options??{},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,b2)=>a.focusOrder-b2.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=component.render(width);maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,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}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve2=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve2,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve2(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}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 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}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,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||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,options){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options?.segment,isAtomic=options?.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();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}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 m2 of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m2[1],10);validIds.has(id)&&markers.push({start:m2.index,end:m2.index+m2[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 j2=0;j2<subChunks.length-1;j2++){let sc=subChunks[j2];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,options={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter3:graphemeSegmenter2,this.validPasteIds())}getPaddingX(){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(`
72
72
  `);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=`\x1B[7m${firstGrapheme}\x1B[0m`;displayText=before+marker+cursor+restAfter}else displayText=before+marker+"\x1B[7m \x1B[0m",lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0)}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?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())}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());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===`
73
73
  `&&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(`
74
74
  `)}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(`
@@ -84,7 +84,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
84
84
  `,{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(`
85
85
  `,{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(`
86
86
  `);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(`
87
- `);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,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.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())},list}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(options){if(!this.autocompleteProvider||options.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(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){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,options)})(),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(options){if(options.explicitTab||options.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,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.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(options.force&&options.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,options.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("@earendil-works/pi-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=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.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=[],options={}){super(children,options)}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},()=>""),x2=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],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.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(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,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===`
87
+ `);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,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.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())},list}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(options){if(!this.autocompleteProvider||options.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(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){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,options)})(),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(options){if(options.explicitTab||options.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,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.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(options.force&&options.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,options.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("@earendil-works/pi-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=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.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=[],options={}){super(children,options)}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},()=>""),x2=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],x2,childWidth,safeWidth))}x2+=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,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),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(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,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===`
88
88
  `){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=`\x1B[7m${this.placeholderStyle(atCursor2)}\x1B[27m`,textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=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=`\x1B[7m${atCursor}\x1B[27m`,textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};var SYMBOLS={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",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(`
89
89
  `).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
90
90
  `).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(`
@@ -106,7 +106,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
106
106
  `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.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 createRequire3}from"node:module";import*as path from"node:path";import{createRequire as createRequire2}from"node:module";import{dirname as dirname3,join as join4}from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";var moduleRequire=createRequire2(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname3(fileURLToPath3(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join4(dirname3(packageEntry),"..",nativePath))}catch{}return candidates.push(join4(moduleDir,"..",nativePath),join4(moduleDir,nativePath),join4(dirname3(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire3(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")}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~";function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.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 seqEnd=1;for(;seqEnd<=remaining.length;){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(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.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){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(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\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(env2=process.env){let configured=Number(env2.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env2.SSH_CONNECTION||env2.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;writeLogPath=(()=>{let env2=process.env.PI_TUI_WRITE_LOG||"";if(!env2)return"";try{if(fs.statSync(env2).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env2,`tui-${ts}-${process.pid}.log`)}}catch{}return env2})();get kittyProtocolActive(){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=>{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(),process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY)}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=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(resolve2=>setTimeout(resolve2,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),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)}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`)}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,b2){let x2=Math.max(a.x,b2.x),y2=Math.max(a.y,b2.y),right=Math.min(a.x+a.width,b2.x+b2.width),bottom=Math.min(a.y+a.height,b2.y+b2.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.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,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,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:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,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,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.box.layer-a.box.layer||b2.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env2=process.env;return process.platform==="darwin"&&env2.SSH_CONNECTION===void 0&&env2.SSH_CLIENT===void 0&&env2.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.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,options={}){super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(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}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),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(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.render(width).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
107
107
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
108
108
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={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(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-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.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.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,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||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,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="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(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.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,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.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(`
109
- `);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,b2)=>b2.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=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,imagesNeedRedraw=screen.some((line,row)=>line!==this.previousScreen[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),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()));buffer+=preparedKittyScreen.evictedImageDeletion;let clearRowsBeforeKittyImages=redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&(!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm");if(clearRowsBeforeKittyImages)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]||(buffer+=`\x1B[${row+1};1H${clearRowsBeforeKittyImages?"":"\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(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
109
+ `);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,b2)=>b2.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=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(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
110
110
  `)}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.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
111
111
  `);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
112
112
  `);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.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"pi-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})
@@ -129,4 +129,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
129
129
  `)}}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(`
130
130
  `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
131
131
  `)}catch{return code.split(`
132
- `).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,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k2=>k2.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getBundledInteractiveAssetPath,getQuickJSWasmPath,getCodemodeWorkerSpecifier,PACKAGE_NAME,APP_NAME,APP_TITLE,CONFIG_DIR_NAME,VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerUrl,getAgentDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath,Z,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,isAppleTerminalSession,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,source_default,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,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,keyDisplayText,keyHint,rawKeyHint};
132
+ `).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,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k2=>k2.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getBundledInteractiveAssetPath,getQuickJSWasmPath,getCodemodeWorkerSpecifier,PACKAGE_NAME,APP_NAME,APP_TITLE,CONFIG_DIR_NAME,VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerUrl,getAgentDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath,Z,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,isAppleTerminalSession,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,source_default,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,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,keyDisplayText,keyHint,rawKeyHint};