@spfunctions/cli 1.7.17 → 1.7.20

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 (180) hide show
  1. package/dist/101.index.js +1 -0
  2. package/dist/12.index.js +1 -0
  3. package/dist/160.index.js +1 -0
  4. package/dist/174.index.js +1 -0
  5. package/dist/278.index.js +6 -0
  6. package/dist/582.index.js +1 -0
  7. package/dist/641.index.js +324 -0
  8. package/dist/669.index.js +1 -0
  9. package/dist/722.index.js +1 -0
  10. package/dist/788.index.js +1 -0
  11. package/dist/816.index.js +12 -0
  12. package/dist/830.index.js +1 -0
  13. package/dist/921.index.js +1 -0
  14. package/dist/index.js +1 -813
  15. package/package.json +6 -2
  16. package/dist/cache.d.ts +0 -6
  17. package/dist/cache.js +0 -31
  18. package/dist/cache.test.d.ts +0 -1
  19. package/dist/cache.test.js +0 -73
  20. package/dist/client.d.ts +0 -56
  21. package/dist/client.js +0 -205
  22. package/dist/client.test.d.ts +0 -1
  23. package/dist/client.test.js +0 -89
  24. package/dist/commands/agent.d.ts +0 -20
  25. package/dist/commands/agent.js +0 -4119
  26. package/dist/commands/announcements.d.ts +0 -3
  27. package/dist/commands/announcements.js +0 -28
  28. package/dist/commands/augment.d.ts +0 -12
  29. package/dist/commands/augment.js +0 -56
  30. package/dist/commands/balance.d.ts +0 -3
  31. package/dist/commands/balance.js +0 -17
  32. package/dist/commands/book.d.ts +0 -17
  33. package/dist/commands/book.js +0 -220
  34. package/dist/commands/cancel.d.ts +0 -5
  35. package/dist/commands/cancel.js +0 -41
  36. package/dist/commands/context.d.ts +0 -6
  37. package/dist/commands/context.js +0 -208
  38. package/dist/commands/create.d.ts +0 -7
  39. package/dist/commands/create.js +0 -42
  40. package/dist/commands/dashboard.d.ts +0 -14
  41. package/dist/commands/dashboard.js +0 -215
  42. package/dist/commands/delta.d.ts +0 -16
  43. package/dist/commands/delta.js +0 -115
  44. package/dist/commands/edges.d.ts +0 -26
  45. package/dist/commands/edges.js +0 -237
  46. package/dist/commands/evaluate.d.ts +0 -4
  47. package/dist/commands/evaluate.js +0 -30
  48. package/dist/commands/explore.d.ts +0 -14
  49. package/dist/commands/explore.js +0 -115
  50. package/dist/commands/feed.d.ts +0 -13
  51. package/dist/commands/feed.js +0 -73
  52. package/dist/commands/fills.d.ts +0 -4
  53. package/dist/commands/fills.js +0 -29
  54. package/dist/commands/forecast.d.ts +0 -4
  55. package/dist/commands/forecast.js +0 -53
  56. package/dist/commands/get.d.ts +0 -5
  57. package/dist/commands/get.js +0 -98
  58. package/dist/commands/heartbeat.d.ts +0 -20
  59. package/dist/commands/heartbeat.js +0 -73
  60. package/dist/commands/history.d.ts +0 -3
  61. package/dist/commands/history.js +0 -38
  62. package/dist/commands/liquidity.d.ts +0 -14
  63. package/dist/commands/liquidity.js +0 -378
  64. package/dist/commands/list.d.ts +0 -5
  65. package/dist/commands/list.js +0 -38
  66. package/dist/commands/login.d.ts +0 -9
  67. package/dist/commands/login.js +0 -98
  68. package/dist/commands/markets.d.ts +0 -10
  69. package/dist/commands/markets.js +0 -39
  70. package/dist/commands/milestones.d.ts +0 -8
  71. package/dist/commands/milestones.js +0 -56
  72. package/dist/commands/orders.d.ts +0 -4
  73. package/dist/commands/orders.js +0 -28
  74. package/dist/commands/performance.d.ts +0 -11
  75. package/dist/commands/performance.js +0 -250
  76. package/dist/commands/positions.d.ts +0 -19
  77. package/dist/commands/positions.js +0 -294
  78. package/dist/commands/prompt.d.ts +0 -13
  79. package/dist/commands/prompt.js +0 -35
  80. package/dist/commands/publish.d.ts +0 -15
  81. package/dist/commands/publish.js +0 -39
  82. package/dist/commands/query.d.ts +0 -15
  83. package/dist/commands/query.js +0 -132
  84. package/dist/commands/rfq.d.ts +0 -5
  85. package/dist/commands/rfq.js +0 -35
  86. package/dist/commands/scan.d.ts +0 -11
  87. package/dist/commands/scan.js +0 -230
  88. package/dist/commands/schedule.d.ts +0 -3
  89. package/dist/commands/schedule.js +0 -38
  90. package/dist/commands/settlements.d.ts +0 -6
  91. package/dist/commands/settlements.js +0 -50
  92. package/dist/commands/setup.d.ts +0 -24
  93. package/dist/commands/setup.js +0 -700
  94. package/dist/commands/signal.d.ts +0 -6
  95. package/dist/commands/signal.js +0 -32
  96. package/dist/commands/strategies.d.ts +0 -11
  97. package/dist/commands/strategies.js +0 -130
  98. package/dist/commands/telegram.d.ts +0 -15
  99. package/dist/commands/telegram.js +0 -125
  100. package/dist/commands/trade.d.ts +0 -12
  101. package/dist/commands/trade.js +0 -112
  102. package/dist/commands/watch.d.ts +0 -19
  103. package/dist/commands/watch.js +0 -157
  104. package/dist/commands/whatif.d.ts +0 -17
  105. package/dist/commands/whatif.js +0 -209
  106. package/dist/commands/x.d.ts +0 -28
  107. package/dist/commands/x.js +0 -167
  108. package/dist/config.d.ts +0 -55
  109. package/dist/config.js +0 -139
  110. package/dist/config.test.d.ts +0 -1
  111. package/dist/config.test.js +0 -138
  112. package/dist/index.d.ts +0 -20
  113. package/dist/kalshi.d.ts +0 -144
  114. package/dist/kalshi.js +0 -498
  115. package/dist/polymarket.d.ts +0 -237
  116. package/dist/polymarket.js +0 -353
  117. package/dist/polymarket.test.d.ts +0 -1
  118. package/dist/polymarket.test.js +0 -424
  119. package/dist/share.d.ts +0 -4
  120. package/dist/share.js +0 -27
  121. package/dist/skills/loader.d.ts +0 -19
  122. package/dist/skills/loader.js +0 -86
  123. package/dist/telegram/agent-bridge.d.ts +0 -15
  124. package/dist/telegram/agent-bridge.js +0 -573
  125. package/dist/telegram/bot.d.ts +0 -10
  126. package/dist/telegram/bot.js +0 -297
  127. package/dist/telegram/commands.d.ts +0 -11
  128. package/dist/telegram/commands.js +0 -120
  129. package/dist/telegram/format.d.ts +0 -11
  130. package/dist/telegram/format.js +0 -51
  131. package/dist/telegram/format.test.d.ts +0 -1
  132. package/dist/telegram/format.test.js +0 -73
  133. package/dist/telegram/poller.d.ts +0 -6
  134. package/dist/telegram/poller.js +0 -32
  135. package/dist/topics.d.ts +0 -17
  136. package/dist/topics.js +0 -102
  137. package/dist/topics.test.d.ts +0 -1
  138. package/dist/topics.test.js +0 -131
  139. package/dist/tui/border.d.ts +0 -33
  140. package/dist/tui/border.js +0 -87
  141. package/dist/tui/chart.d.ts +0 -19
  142. package/dist/tui/chart.js +0 -117
  143. package/dist/tui/dashboard.d.ts +0 -9
  144. package/dist/tui/dashboard.js +0 -814
  145. package/dist/tui/layout.d.ts +0 -16
  146. package/dist/tui/layout.js +0 -41
  147. package/dist/tui/screen.d.ts +0 -33
  148. package/dist/tui/screen.js +0 -102
  149. package/dist/tui/state.d.ts +0 -40
  150. package/dist/tui/state.js +0 -36
  151. package/dist/tui/widgets/commandbar.d.ts +0 -8
  152. package/dist/tui/widgets/commandbar.js +0 -82
  153. package/dist/tui/widgets/detail.d.ts +0 -9
  154. package/dist/tui/widgets/detail.js +0 -151
  155. package/dist/tui/widgets/edges.d.ts +0 -4
  156. package/dist/tui/widgets/edges.js +0 -34
  157. package/dist/tui/widgets/liquidity.d.ts +0 -9
  158. package/dist/tui/widgets/liquidity.js +0 -142
  159. package/dist/tui/widgets/orders.d.ts +0 -4
  160. package/dist/tui/widgets/orders.js +0 -37
  161. package/dist/tui/widgets/portfolio.d.ts +0 -4
  162. package/dist/tui/widgets/portfolio.js +0 -59
  163. package/dist/tui/widgets/signals.d.ts +0 -4
  164. package/dist/tui/widgets/signals.js +0 -31
  165. package/dist/tui/widgets/statusbar.d.ts +0 -8
  166. package/dist/tui/widgets/statusbar.js +0 -72
  167. package/dist/tui/widgets/thesis.d.ts +0 -4
  168. package/dist/tui/widgets/thesis.js +0 -66
  169. package/dist/tui/widgets/trade.d.ts +0 -9
  170. package/dist/tui/widgets/trade.js +0 -117
  171. package/dist/tui/widgets/upcoming.d.ts +0 -4
  172. package/dist/tui/widgets/upcoming.js +0 -41
  173. package/dist/tui/widgets/whatif.d.ts +0 -7
  174. package/dist/tui/widgets/whatif.js +0 -113
  175. package/dist/types/output.d.ts +0 -412
  176. package/dist/types/output.js +0 -9
  177. package/dist/utils.d.ts +0 -42
  178. package/dist/utils.js +0 -124
  179. package/dist/utils.test.d.ts +0 -1
  180. package/dist/utils.test.js +0 -111
@@ -0,0 +1 @@
1
+ "use strict";exports.id=921,exports.ids=[921],exports.modules={93921:(t,e,s)=>{s.r(e),s.d(e,{Box:()=>nt,CURSOR_MARKER:()=>ke,CancellableLoader:()=>qt,CombinedAutocompleteProvider:()=>g,Container:()=>Ce,DEFAULT_EDITOR_KEYBINDINGS:()=>Ft,Editor:()=>Ie,EditorKeybindingsManager:()=>_t,Image:()=>Te,Input:()=>Re,Key:()=>ht,Loader:()=>Ht,Markdown:()=>Vs,ProcessTerminal:()=>ti,SelectList:()=>Le,SettingsList:()=>Hs,Spacer:()=>qs,StdinBuffer:()=>Ys,TUI:()=>we,Text:()=>Vt,TruncatedText:()=>js,allocateImageId:()=>ne,calculateImageRows:()=>ae,decodeKittyPrintable:()=>Et,deleteAllKittyImages:()=>le,deleteKittyImage:()=>oe,detectCapabilities:()=>Jt,encodeITerm2:()=>he,encodeKitty:()=>re,fuzzyFilter:()=>h,fuzzyMatch:()=>l,getCapabilities:()=>te,getCellDimensions:()=>Zt,getEditorKeybindings:()=>zt,getGifDimensions:()=>de,getImageDimensions:()=>fe,getJpegDimensions:()=>ue,getPngDimensions:()=>ce,getWebpDimensions:()=>pe,imageFallback:()=>me,isFocusable:()=>xe,isKeyRelease:()=>vt,isKeyRepeat:()=>yt,isKittyProtocolActive:()=>lt,matchesKey:()=>Pt,parseKey:()=>Bt,renderImage:()=>ge,resetCapabilitiesCache:()=>ee,setCellDimensions:()=>Yt,setEditorKeybindings:()=>Ut,setKittyProtocolActive:()=>ot,truncateToWidth:()=>tt,visibleWidth:()=>H,wrapTextWithAnsi:()=>N});var i=s(35317),n=s(79896),r=s(70857),o=s(16928);function l(t,e){const s=t.toLowerCase(),i=e.toLowerCase(),n=t=>{if(0===t.length)return{matches:!0,score:0};if(t.length>i.length)return{matches:!1,score:0};let e=0,s=0,n=-1,r=0;for(let o=0;o<i.length&&e<t.length;o++)if(i[o]===t[e]){n===o-1?(r++,s-=5*r):(r=0,n>=0&&(s+=2*(o-n-1))),(0===o||/[\s\-_./:]/.test(i[o-1]))&&(s-=10),s+=.1*o,n=o,e++}return e<t.length?{matches:!1,score:0}:{matches:!0,score:s}},r=n(s);if(r.matches)return r;const o=s.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),l=s.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),h=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:l?`${l.groups?.letters??""}${l.groups?.digits??""}`:"";if(!h)return r;const a=n(h);return a.matches?{matches:!0,score:a.score+5}:r}function h(t,e,s){if(!e.trim())return t;const i=e.trim().split(/\s+/).filter(t=>t.length>0);if(0===i.length)return t;const n=[];for(const e of t){const t=s(e);let r=0,o=!0;for(const e of i){const s=l(e,t);if(!s.matches){o=!1;break}r+=s.score}o&&n.push({item:e,totalScore:r})}return n.sort((t,e)=>t.totalScore-e.totalScore),n.map(t=>t.item)}const a=new Set([" ","\t",'"',"'","="]);function c(t){for(let e=t.length-1;e>=0;e-=1)if(a.has(t[e]??""))return e;return-1}function u(t,e){return 0===e||a.has(t[e-1]??"")}function d(t){const e=function(t){let e=!1,s=-1;for(let i=0;i<t.length;i+=1)'"'===t[i]&&(e=!e,e&&(s=i));return e?s:null}(t);return null===e?null:e>0&&"@"===t[e-1]?u(t,e-1)?t.slice(e-1):null:u(t,e)?t.slice(e):null}function p(t){return t.startsWith('@"')?{rawPrefix:t.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:t.startsWith('"')?{rawPrefix:t.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:t.startsWith("@")?{rawPrefix:t.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:t,isAtPrefix:!1,isQuotedPrefix:!1}}function f(t,e){const s=e.isQuotedPrefix||t.includes(" "),i=e.isAtPrefix?"@":"";if(!s)return`${i}${t}`;return`${`${i}"`}${t}"`}class g{commands;basePath;fdPath;constructor(t=[],e=process.cwd(),s=null){this.commands=t,this.basePath=e,this.fdPath=s}getSuggestions(t,e,s){const i=(t[e]||"").slice(0,s),n=this.extractAtPrefix(i);if(n){const{rawPrefix:t,isQuotedPrefix:e}=p(n),s=this.getFuzzyFileSuggestions(t,{isQuotedPrefix:e});return 0===s.length?null:{items:s,prefix:n}}if(i.startsWith("/")){const t=i.indexOf(" ");if(-1===t){const t=i.slice(1),e=h(this.commands.map(t=>({name:"name"in t?t.name:t.value,label:"name"in t?t.name:t.label,description:t.description})),t,t=>t.name).map(t=>({value:t.name,label:t.label,...t.description&&{description:t.description}}));return 0===e.length?null:{items:e,prefix:i}}{const e=i.slice(1,t),s=i.slice(t+1),n=this.commands.find(t=>("name"in t?t.name:t.value)===e);if(!n||!("getArgumentCompletions"in n)||!n.getArgumentCompletions)return null;const r=n.getArgumentCompletions(s);return r&&0!==r.length?{items:r,prefix:s}:null}}const r=this.extractPathPrefix(i,!1);if(null!==r){const t=this.getFileSuggestions(r);return 0===t.length?null:(1!==t.length||t[0]?.value!==r||r.endsWith("/"),{items:t,prefix:r})}return null}applyCompletion(t,e,s,i,n){const r=t[e]||"",o=r.slice(0,s-n.length),l=r.slice(s),h=n.startsWith('"')||n.startsWith('@"'),a=l.startsWith('"'),c=i.value.endsWith('"'),u=h&&c&&a?l.slice(1):l;if(n.startsWith("/")&&""===o.trim()&&!n.slice(1).includes("/")){const s=`${o}/${i.value} ${u}`,n=[...t];return n[e]=s,{lines:n,cursorLine:e,cursorCol:o.length+i.value.length+2}}if(n.startsWith("@")){const s=i.label.endsWith("/"),n=s?"":" ",r=`${o+i.value}${n}${u}`,l=[...t];l[e]=r;const h=i.value.endsWith('"'),a=s&&h?i.value.length-1:i.value.length;return{lines:l,cursorLine:e,cursorCol:o.length+a+n.length}}const d=r.slice(0,s);if(d.includes("/")&&d.includes(" ")){const s=o+i.value+u,n=[...t];n[e]=s;const r=i.label.endsWith("/"),l=i.value.endsWith('"'),h=r&&l?i.value.length-1:i.value.length;return{lines:n,cursorLine:e,cursorCol:o.length+h}}const p=o+i.value+u,f=[...t];f[e]=p;const g=i.label.endsWith("/"),m=i.value.endsWith('"'),x=g&&m?i.value.length-1:i.value.length;return{lines:f,cursorLine:e,cursorCol:o.length+x}}extractAtPrefix(t){const e=d(t);if(e?.startsWith('@"'))return e;const s=c(t),i=-1===s?0:s+1;return"@"===t[i]?t.slice(i):null}extractPathPrefix(t,e=!1){const s=d(t);if(s)return s;const i=c(t),n=-1===i?t:t.slice(i+1);return e||n.includes("/")||n.startsWith(".")||n.startsWith("~/")||""===n&&t.endsWith(" ")?n:null}expandHomePath(t){if(t.startsWith("~/")){const e=(0,o.join)((0,r.homedir)(),t.slice(2));return t.endsWith("/")&&!e.endsWith("/")?`${e}/`:e}return"~"===t?(0,r.homedir)():t}resolveScopedFuzzyQuery(t){const e=t.lastIndexOf("/");if(-1===e)return null;const s=t.slice(0,e+1),i=t.slice(e+1);let r;r=s.startsWith("~/")?this.expandHomePath(s):s.startsWith("/")?s:(0,o.join)(this.basePath,s);try{if(!(0,n.statSync)(r).isDirectory())return null}catch{return null}return{baseDir:r,query:i,displayBase:s}}scopedPathForDisplay(t,e){return"/"===t?`/${e}`:`${t}${e}`}getFileSuggestions(t){try{let e,s;const{rawPrefix:i,isAtPrefix:r,isQuotedPrefix:l}=p(t);let h=i;h.startsWith("~")&&(h=this.expandHomePath(h));if(""===i||"./"===i||"../"===i||"~"===i||"~/"===i||"/"===i||r&&""===i)e=i.startsWith("~")||h.startsWith("/")?h:(0,o.join)(this.basePath,h),s="";else if(i.endsWith("/"))e=i.startsWith("~")||h.startsWith("/")?h:(0,o.join)(this.basePath,h),s="";else{const t=(0,o.dirname)(h),n=(0,o.basename)(h);e=i.startsWith("~")||h.startsWith("/")?t:(0,o.join)(this.basePath,t),s=n}const a=(0,n.readdirSync)(e,{withFileTypes:!0}),c=[];for(const t of a){if(!t.name.toLowerCase().startsWith(s.toLowerCase()))continue;let h,a=t.isDirectory();if(!a&&t.isSymbolicLink())try{const s=(0,o.join)(e,t.name);a=(0,n.statSync)(s).isDirectory()}catch{}const u=t.name,d=i;if(d.endsWith("/"))h=d+u;else if(d.includes("/"))if(d.startsWith("~/")){const t=d.slice(2),e=(0,o.dirname)(t);h=`~/${"."===e?u:(0,o.join)(e,u)}`}else if(d.startsWith("/")){const t=(0,o.dirname)(d);h="/"===t?`/${u}`:`${t}/${u}`}else h=(0,o.join)((0,o.dirname)(d),u);else h=d.startsWith("~")?`~/${u}`:u;const p=f(a?`${h}/`:h,{isDirectory:a,isAtPrefix:r,isQuotedPrefix:l});c.push({value:p,label:u+(a?"/":"")})}return c.sort((t,e)=>{const s=t.value.endsWith("/"),i=e.value.endsWith("/");return s&&!i?-1:!s&&i?1:t.label.localeCompare(e.label)}),c}catch(t){return[]}}scoreEntry(t,e,s){const i=(0,o.basename)(t).toLowerCase(),n=e.toLowerCase();let r=0;return i===n?r=100:i.startsWith(n)?r=80:i.includes(n)?r=50:t.toLowerCase().includes(n)&&(r=30),s&&r>0&&(r+=10),r}getFuzzyFileSuggestions(t,e){if(!this.fdPath)return[];try{const s=this.resolveScopedFuzzyQuery(t),n=s?.baseDir??this.basePath,r=s?.query??t,l=function(t,e,s,n){const r=["--base-directory",t,"--max-results",String(n),"--type","f","--type","d","--full-path","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];s&&r.push(s);const o=(0,i.spawnSync)(e,r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],maxBuffer:10485760});if(0!==o.status||!o.stdout)return[];const l=o.stdout.trim().split("\n").filter(Boolean),h=[];for(const t of l){const e=t.endsWith("/")?t.slice(0,-1):t;if(".git"===e||e.startsWith(".git/")||e.includes("/.git/"))continue;const s=t.endsWith("/");h.push({path:t,isDirectory:s})}return h}(n,this.fdPath,r,100),h=l.map(t=>({...t,score:r?this.scoreEntry(t.path,r,t.isDirectory):1})).filter(t=>t.score>0);h.sort((t,e)=>e.score-t.score);const a=h.slice(0,20),c=[];for(const{path:t,isDirectory:i}of a){const n=i?t.slice(0,-1):t,r=s?this.scopedPathForDisplay(s.displayBase,n):n,l=(0,o.basename)(n),h=f(i?`${r}/`:r,{isDirectory:i,isAtPrefix:!0,isQuotedPrefix:e.isQuotedPrefix});c.push({value:h,label:l+(i?"/":""),description:r})}return c}catch{return[]}}getForceFileSuggestions(t,e,s){const i=(t[e]||"").slice(0,s);if(i.trim().startsWith("/")&&!i.trim().includes(" "))return null;const n=this.extractPathPrefix(i,!0);if(null!==n){const t=this.getFileSuggestions(n);return 0===t.length?null:{items:t,prefix:n}}return null}shouldTriggerFileCompletion(t,e,s){const i=(t[e]||"").slice(0,s);return!(i.trim().startsWith("/")&&!i.trim().includes(" "))}}const m=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],x=[12288,12288,65281,65376,65504,65510],k=[8361,8361,65377,65470,65474,65479,65482,65487,65490,65495,65498,65500,65512,65518],b=[32,126,162,163,165,166,172,172,175,175,10214,10221,10629,10630],C=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],w=(t,e)=>{let s=0,i=Math.floor(t.length/2)-1;for(;s<=i;){const n=Math.floor((s+i)/2),r=2*n;if(e<t[r])i=n-1;else{if(!(e>t[r+1]))return!0;s=n+1}}return!1},v=m[0],y=m.at(-1),L=x[0],S=x.at(-1),$=(k[0],k.at(-1),b[0],b.at(-1),C[0]),I=C.at(-1),[T,A]=function(t){let e=t[0],s=t[1];for(let i=0;i<t.length;i+=2){const n=t[i],r=t[i+1];if(19968>=n&&19968<=r)return[n,r];r-n>s-e&&(e=n,s=r)}return[e,s]}(C);const R=t=>!(t<v||t>y)&&w(m,t),P=t=>!(t<L||t>S)&&w(x,t),M=t=>t>=T&&t<=A||!(t<$||t>I)&&w(C,t);function B(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function W(t,{ambiguousAsWide:e=!1}={}){return B(t),P(t)||M(t)||e&&R(t)?2:1}const O=new Intl.Segmenter(void 0,{granularity:"grapheme"});function E(){return O}const F=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v,_=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,D=/^\p{RGI_Emoji}$/v,z=512,U=new Map;function V(t){if(F.test(t))return 0;if(function(t){const e=t.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||t.includes("️")||t.length>2}(t)&&D.test(t))return 2;const e=t.replace(_,"").codePointAt(0);if(void 0===e)return 0;if(e>=127462&&e<=127487)return 2;let s=W(e);if(t.length>1)for(const e of t.slice(1)){const t=e.codePointAt(0);t>=65280&&t<=65519&&(s+=W(t))}return s}function H(t){if(0===t.length)return 0;let e=!0;for(let s=0;s<t.length;s++){const i=t.charCodeAt(s);if(i<32||i>126){e=!1;break}}if(e)return t.length;const s=U.get(t);if(void 0!==s)return s;let i=t;if(t.includes("\t")&&(i=i.replace(/\t/g," ")),i.includes("")){let t="",e=0;for(;e<i.length;){const s=q(i,e);s?e+=s.length:(t+=i[e],e++)}i=t}let n=0;for(const{segment:t}of O.segment(i))n+=V(t);if(U.size>=z){const t=U.keys().next().value;void 0!==t&&U.delete(t)}return U.set(t,n),n}function q(t,e){if(e>=t.length||""!==t[e])return null;const s=t[e+1];if("["===s){let s=e+2;for(;s<t.length&&!/[mGKHJ]/.test(t[s]);)s++;return s<t.length?{code:t.substring(e,s+1),length:s+1-e}:null}if("]"===s){let s=e+2;for(;s<t.length;){if(""===t[s])return{code:t.substring(e,s+1),length:s+1-e};if(""===t[s]&&"\\"===t[s+1])return{code:t.substring(e,s+2),length:s+2-e};s++}return null}if("_"===s){let s=e+2;for(;s<t.length;){if(""===t[s])return{code:t.substring(e,s+1),length:s+1-e};if(""===t[s]&&"\\"===t[s+1])return{code:t.substring(e,s+2),length:s+2-e};s++}return null}return null}class j{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;process(t){if(!t.endsWith("m"))return;const e=t.match(/\x1b\[([\d;]*)m/);if(!e)return;const s=e[1];if(""===s||"0"===s)return void this.reset();const i=s.split(";");let n=0;for(;n<i.length;){const t=Number.parseInt(i[n],10);if(38===t||48===t){if("5"===i[n+1]&&void 0!==i[n+2]){const e=`${i[n]};${i[n+1]};${i[n+2]}`;38===t?this.fgColor=e:this.bgColor=e,n+=3;continue}if("2"===i[n+1]&&void 0!==i[n+4]){const e=`${i[n]};${i[n+1]};${i[n+2]};${i[n+3]};${i[n+4]}`;38===t?this.fgColor=e:this.bgColor=e,n+=5;continue}}switch(t){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:t>=30&&t<=37||t>=90&&t<=97?this.fgColor=String(t):(t>=40&&t<=47||t>=100&&t<=107)&&(this.bgColor=String(t))}n++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset()}getActiveCodes(){const t=[];return this.bold&&t.push("1"),this.dim&&t.push("2"),this.italic&&t.push("3"),this.underline&&t.push("4"),this.blink&&t.push("5"),this.inverse&&t.push("7"),this.hidden&&t.push("8"),this.strikethrough&&t.push("9"),this.fgColor&&t.push(this.fgColor),this.bgColor&&t.push(this.bgColor),0===t.length?"":`[${t.join(";")}m`}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||null!==this.fgColor||null!==this.bgColor}getLineEndReset(){return this.underline?"":""}}function K(t,e){let s=0;for(;s<t.length;){const i=q(t,s);i?(e.process(i.code),s+=i.length):s++}}function N(t,e){if(!t)return[""];const s=t.split("\n"),i=[],n=new j;for(const t of s){const s=i.length>0?n.getActiveCodes():"";i.push(...G(s+t,e)),K(t,n)}return i.length>0?i:[""]}function G(t,e){if(!t)return[""];if(H(t)<=e)return[t];const s=[],i=new j,n=function(t){const e=[];let s="",i="",n=!1,r=0;for(;r<t.length;){const o=q(t,r);if(o){i+=o.code,r+=o.length;continue}const l=t[r],h=" "===l;h!==n&&s&&(e.push(s),s=""),i&&(s+=i,i=""),n=h,s+=l,r++}return i&&(s+=i),s&&e.push(s),e}(t);let r="",o=0;for(const t of n){const n=H(t),l=""===t.trim();if(n>e&&!l){if(r){const t=i.getLineEndReset();t&&(r+=t),s.push(r),r="",o=0}const n=Y(t,e,i);s.push(...n.slice(0,-1)),r=n[n.length-1],o=H(r);continue}if(o+n>e&&o>0){let e=r.trimEnd();const h=i.getLineEndReset();h&&(e+=h),s.push(e),l?(r=i.getActiveCodes(),o=0):(r=i.getActiveCodes()+t,o=n)}else r+=t,o+=n;K(t,i)}return r&&s.push(r),s.length>0?s.map(t=>t.trimEnd()):[""]}const X=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function Q(t){return/\s/.test(t)}function Z(t){return X.test(t)}function Y(t,e,s){const i=[];let n=s.getActiveCodes(),r=0,o=0;const l=[];for(;o<t.length;){const e=q(t,o);if(e)l.push({type:"ansi",value:e.code}),o+=e.length;else{let e=o;for(;e<t.length;){if(q(t,e))break;e++}const s=t.slice(o,e);for(const t of O.segment(s))l.push({type:"grapheme",value:t.segment});o=e}}for(const t of l){if("ansi"===t.type){n+=t.value,s.process(t.value);continue}const o=t.value;if(!o)continue;const l=H(o);if(r+l>e){const t=s.getLineEndReset();t&&(n+=t),i.push(n),n=s.getActiveCodes(),r=0}n+=o,r+=l}return n&&i.push(n),i.length>0?i:[""]}function J(t,e,s){const i=H(t),n=Math.max(0,e-i);return s(t+" ".repeat(n))}function tt(t,e,s="...",i=!1){const n=H(t);if(n<=e)return i?t+" ".repeat(e-n):t;const r=e-H(s);if(r<=0)return s.substring(0,e);let o=0;const l=[];for(;o<t.length;){const e=q(t,o);if(e)l.push({type:"ansi",value:e.code}),o+=e.length;else{let e=o;for(;e<t.length;){if(q(t,e))break;e++}const s=t.slice(o,e);for(const t of O.segment(s))l.push({type:"grapheme",value:t.segment});o=e}}let h="",a=0;for(const t of l){if("ansi"===t.type){h+=t.value;continue}const e=t.value;if(!e)continue;const s=H(e);if(a+s>r)break;h+=e,a+=s}const c=`${h}${s}`;if(i){const t=H(c);return c+" ".repeat(Math.max(0,e-t))}return c}function et(t,e,s,i=!1){return st(t,e,s,i).text}function st(t,e,s,i=!1){if(s<=0)return{text:"",width:0};const n=e+s;let r="",o=0,l=0,h=0,a="";for(;h<t.length;){const s=q(t,h);if(s){l>=e&&l<n?r+=s.code:l<e&&(a+=s.code),h+=s.length;continue}let c=h;for(;c<t.length&&!q(t,c);)c++;for(const{segment:s}of O.segment(t.slice(h,c))){const t=V(s);if(l>=e&&l<n&&(!i||l+t<=n)&&(a&&(r+=a,a=""),r+=s,o+=t),l+=t,l>=n)break}if(h=c,l>=n)break}return{text:r,width:o}}const it=new j;class nt{children=[];paddingX;paddingY;bgFn;cache;constructor(t=1,e=1,s){this.paddingX=t,this.paddingY=e,this.bgFn=s}addChild(t){this.children.push(t),this.invalidateCache()}removeChild(t){const e=this.children.indexOf(t);-1!==e&&(this.children.splice(e,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(t){this.bgFn=t}invalidateCache(){this.cache=void 0}matchCache(t,e,s){const i=this.cache;return!!i&&i.width===t&&i.bgSample===s&&i.childLines.length===e.length&&i.childLines.every((t,s)=>t===e[s])}invalidate(){this.invalidateCache();for(const t of this.children)t.invalidate?.()}render(t){if(0===this.children.length)return[];const e=Math.max(1,t-2*this.paddingX),s=" ".repeat(this.paddingX),i=[];for(const t of this.children){const n=t.render(e);for(const t of n)i.push(s+t)}if(0===i.length)return[];const n=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(t,i,n))return this.cache.lines;const r=[];for(let e=0;e<this.paddingY;e++)r.push(this.applyBg("",t));for(const e of i)r.push(this.applyBg(e,t));for(let e=0;e<this.paddingY;e++)r.push(this.applyBg("",t));return this.cache={childLines:i,width:t,bgSample:n,lines:r},r}applyBg(t,e){const s=H(t),i=Math.max(0,e-s),n=t+" ".repeat(i);return this.bgFn?J(n,e,this.bgFn):n}}let rt=!1;function ot(t){rt=t}function lt(){return rt}const ht={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:t=>`ctrl+${t}`,shift:t=>`shift+${t}`,alt:t=>`alt+${t}`,ctrlShift:t=>`ctrl+shift+${t}`,shiftCtrl:t=>`shift+ctrl+${t}`,ctrlAlt:t=>`ctrl+alt+${t}`,altCtrl:t=>`alt+ctrl+${t}`,shiftAlt:t=>`shift+alt+${t}`,altShift:t=>`alt+shift+${t}`,ctrlShiftAlt:t=>`ctrl+shift+alt+${t}`},at=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),ct={shift:1,alt:2,ctrl:4},ut=192,dt={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},pt={up:-1,down:-2,right:-3,left:-4},ft={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},gt={up:["","OA"],down:["","OB"],right:["","OC"],left:["","OD"],home:["","OH","[1~","[7~"],end:["","OF","[4~","[8~"],insert:["[2~"],delete:["[3~"],pageUp:["[5~","[[5~"],pageDown:["[6~","[[6~"],clear:["","OE"],f1:["OP","[11~","[[A"],f2:["OQ","[12~","[[B"],f3:["OR","[13~","[[C"],f4:["OS","[14~","[[D"],f5:["[15~","[[E"],f6:["[17~"],f7:["[18~"],f8:["[19~"],f9:["[20~"],f10:["[21~"],f11:["[23~"],f12:["[24~"]},mt={up:[""],down:[""],right:[""],left:[""],clear:[""],insert:["[2$"],delete:["[3$"],pageUp:["[5$"],pageDown:["[6$"],home:["[7$"],end:["[8$"]},xt={up:["Oa"],down:["Ob"],right:["Oc"],left:["Od"],clear:["Oe"],insert:["[2^"],delete:["[3^"],pageUp:["[5^"],pageDown:["[6^"],home:["[7^"],end:["[8^"]},kt={"OA":"up","OB":"down","OC":"right","OD":"left","OH":"home","OF":"end","":"clear","OE":"clear","Oe":"ctrl+clear","":"shift+clear","[2~":"insert","[2$":"shift+insert","[2^":"ctrl+insert","[3$":"shift+delete","[3^":"ctrl+delete","[[5~":"pageUp","[[6~":"pageDown","":"shift+up","":"shift+down","":"shift+right","":"shift+left","Oa":"ctrl+up","Ob":"ctrl+down","Oc":"ctrl+right","Od":"ctrl+left","[5$":"shift+pageUp","[6$":"shift+pageDown","[7$":"shift+home","[8$":"shift+end","[5^":"ctrl+pageUp","[6^":"ctrl+pageDown","[7^":"ctrl+home","[8^":"ctrl+end","OP":"f1","OQ":"f2","OR":"f3","OS":"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","b":"alt+left","f":"alt+right","p":"alt+up","n":"alt+down"},bt=(t,e)=>e.includes(t),Ct=(t,e,s)=>s===ct.shift?bt(t,mt[e]):s===ct.ctrl&&bt(t,xt[e]);let wt="press";function vt(t){return!t.includes("[200~")&&!!(t.includes(":3u")||t.includes(":3~")||t.includes(":3A")||t.includes(":3B")||t.includes(":3C")||t.includes(":3D")||t.includes(":3H")||t.includes(":3F"))}function yt(t){return!t.includes("[200~")&&!!(t.includes(":2u")||t.includes(":2~")||t.includes(":2A")||t.includes(":2B")||t.includes(":2C")||t.includes(":2D")||t.includes(":2H")||t.includes(":2F"))}function Lt(t){if(!t)return"press";const e=parseInt(t,10);return 2===e?"repeat":3===e?"release":"press"}function St(t){const e=t.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){const t=parseInt(e[1],10),s=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,i=e[3]?parseInt(e[3],10):void 0,n=e[4]?parseInt(e[4],10):1,r=Lt(e[5]);return wt=r,{codepoint:t,shiftedKey:s,baseLayoutKey:i,modifier:n-1,eventType:r}}const s=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(s){const t=parseInt(s[1],10),e=Lt(s[2]);return wt=e,{codepoint:{A:-1,B:-2,C:-3,D:-4}[s[3]],modifier:t-1,eventType:e}}const i=t.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){const t=parseInt(i[1],10),e=i[2]?parseInt(i[2],10):1,s=Lt(i[3]),n={2:ft.insert,3:ft.delete,5:ft.pageUp,6:ft.pageDown,7:ft.home,8:ft.end}[t];if(void 0!==n)return wt=s,{codepoint:n,modifier:e-1,eventType:s}}const n=t.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(n){const t=parseInt(n[1],10),e=Lt(n[2]),s="H"===n[3]?ft.home:ft.end;return wt=e,{codepoint:s,modifier:t-1,eventType:e}}return null}function $t(t,e,s){const i=St(t);if(!i)return!1;if((i.modifier&~ut)!==(s&~ut))return!1;if(i.codepoint===e)return!0;if(void 0!==i.baseLayoutKey&&i.baseLayoutKey===e){const t=i.codepoint,e=t>=97&&t<=122,s=at.has(String.fromCharCode(t));if(!e&&!s)return!0}return!1}function It(t){const e=t.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;const s=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:s-1}}function Tt(t,e,s){const i=It(t);return!!i&&(i.codepoint===e&&i.modifier===s)}function At(t){return t>="0"&&t<="9"}function Rt(t,e,s){return 0!==s&&Tt(t,e,s)}function Pt(t,e){const s=function(t){const e=t.toLowerCase().split("+"),s=e[e.length-1];return s?{key:s,ctrl:e.includes("ctrl"),shift:e.includes("shift"),alt:e.includes("alt")}:null}(e);if(!s)return!1;const{key:i,ctrl:n,shift:r,alt:o}=s;let l=0;switch(r&&(l|=ct.shift),o&&(l|=ct.alt),n&&(l|=ct.ctrl),i){case"escape":case"esc":return 0===l&&(""===t||$t(t,dt.escape,0));case"space":if(!rt){if(n&&!o&&!r&&"\0"===t)return!0;if(o&&!n&&!r&&" "===t)return!0}return 0===l?" "===t||$t(t,dt.space,0):$t(t,dt.space,l);case"tab":return!r||n||o?0===l?"\t"===t||$t(t,dt.tab,0):$t(t,dt.tab,l):""===t||$t(t,dt.tab,ct.shift);case"enter":case"return":return!r||n||o?!o||n||r?0===l?"\r"===t||!rt&&"\n"===t||"OM"===t||$t(t,dt.enter,0)||$t(t,dt.kpEnter,0):$t(t,dt.enter,l)||$t(t,dt.kpEnter,l)||Tt(t,dt.enter,l):!(!$t(t,dt.enter,ct.alt)&&!$t(t,dt.kpEnter,ct.alt))||(!!Tt(t,dt.enter,ct.alt)||!rt&&"\r"===t):!(!$t(t,dt.enter,ct.shift)&&!$t(t,dt.kpEnter,ct.shift))||(!!Tt(t,dt.enter,ct.shift)||!!rt&&("\r"===t||"\n"===t));case"backspace":return!o||n||r?0===l?""===t||"\b"===t||$t(t,dt.backspace,0):$t(t,dt.backspace,l):""===t||"\b"===t||$t(t,dt.backspace,ct.alt);case"insert":return 0===l?bt(t,gt.insert)||$t(t,ft.insert,0):!!Ct(t,"insert",l)||$t(t,ft.insert,l);case"delete":return 0===l?bt(t,gt.delete)||$t(t,ft.delete,0):!!Ct(t,"delete",l)||$t(t,ft.delete,l);case"clear":return 0===l?bt(t,gt.clear):Ct(t,"clear",l);case"home":return 0===l?bt(t,gt.home)||$t(t,ft.home,0):!!Ct(t,"home",l)||$t(t,ft.home,l);case"end":return 0===l?bt(t,gt.end)||$t(t,ft.end,0):!!Ct(t,"end",l)||$t(t,ft.end,l);case"pageup":return 0===l?bt(t,gt.pageUp)||$t(t,ft.pageUp,0):!!Ct(t,"pageUp",l)||$t(t,ft.pageUp,l);case"pagedown":return 0===l?bt(t,gt.pageDown)||$t(t,ft.pageDown,0):!!Ct(t,"pageDown",l)||$t(t,ft.pageDown,l);case"up":return!o||n||r?0===l?bt(t,gt.up)||$t(t,pt.up,0):!!Ct(t,"up",l)||$t(t,pt.up,l):"p"===t||$t(t,pt.up,ct.alt);case"down":return!o||n||r?0===l?bt(t,gt.down)||$t(t,pt.down,0):!!Ct(t,"down",l)||$t(t,pt.down,l):"n"===t||$t(t,pt.down,ct.alt);case"left":return!o||n||r?!n||o||r?0===l?bt(t,gt.left)||$t(t,pt.left,0):!!Ct(t,"left",l)||$t(t,pt.left,l):""===t||Ct(t,"left",ct.ctrl)||$t(t,pt.left,ct.ctrl):""===t||!rt&&"B"===t||"b"===t||$t(t,pt.left,ct.alt);case"right":return!o||n||r?!n||o||r?0===l?bt(t,gt.right)||$t(t,pt.right,0):!!Ct(t,"right",l)||$t(t,pt.right,l):""===t||Ct(t,"right",ct.ctrl)||$t(t,pt.right,ct.ctrl):""===t||!rt&&"F"===t||"f"===t||$t(t,pt.right,ct.alt);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":if(0!==l)return!1;return bt(t,gt[i])}if(1===i.length&&(i>="a"&&i<="z"||At(i)||at.has(i))){const e=i.charCodeAt(0),s=function(t){const e=t.toLowerCase(),s=e.charCodeAt(0);return s>=97&&s<=122||"["===e||"\\"===e||"]"===e||"_"===e?String.fromCharCode(31&s):"-"===e?String.fromCharCode(31):null}(i),h=i>="a"&&i<="z",a=At(i);return n&&o&&!r&&!rt&&s?t===`${s}`:!(!o||n||r||rt||!h&&!a||t!==`${i}`)||(!n||r||o?n&&r&&!o?$t(t,e,ct.shift+ct.ctrl)||Rt(t,e,ct.shift+ct.ctrl):!r||n||o?0!==l?$t(t,e,l)||Rt(t,e,l):t===i||$t(t,e,0):!(!h||t!==i.toUpperCase())||($t(t,e,ct.shift)||Rt(t,e,ct.shift)):!(!s||t!==s)||($t(t,e,ct.ctrl)||Rt(t,e,ct.ctrl)))}return!1}function Mt(t,e,s){const i=t>=97&&t<=122,n=t>=48&&t<=57,r=at.has(String.fromCharCode(t)),o=i||n||r?t:s??t;let l;if(o===dt.escape?l="escape":o===dt.tab?l="tab":o===dt.enter||o===dt.kpEnter?l="enter":o===dt.space?l="space":o===dt.backspace?l="backspace":o===ft.delete?l="delete":o===ft.insert?l="insert":o===ft.home?l="home":o===ft.end?l="end":o===ft.pageUp?l="pageUp":o===ft.pageDown?l="pageDown":o===pt.up?l="up":o===pt.down?l="down":o===pt.left?l="left":o===pt.right?l="right":(o>=48&&o<=57||o>=97&&o<=122||at.has(String.fromCharCode(o)))&&(l=String.fromCharCode(o)),l)return function(t,e){const s=[],i=e&~ut;if(0===(i&~(ct.shift|ct.ctrl|ct.alt)))return i&ct.shift&&s.push("shift"),i&ct.ctrl&&s.push("ctrl"),i&ct.alt&&s.push("alt"),s.length>0?`${s.join("+")}+${t}`:t}(l,e)}function Bt(t){const e=St(t);if(e)return Mt(e.codepoint,e.modifier,e.baseLayoutKey);const s=It(t);if(s)return Mt(s.codepoint,s.modifier);if(rt&&("\r"===t||"\n"===t))return"shift+enter";const i=kt[t];if(i)return i;if(""===t)return"escape";if(""===t)return"ctrl+\\";if(""===t)return"ctrl+]";if(""===t)return"ctrl+-";if(""===t)return"ctrl+alt+[";if(""===t)return"ctrl+alt+\\";if(""===t)return"ctrl+alt+]";if(""===t)return"ctrl+alt+-";if("\t"===t)return"tab";if("\r"===t||!rt&&"\n"===t||"OM"===t)return"enter";if("\0"===t)return"ctrl+space";if(" "===t)return"space";if(""===t||"\b"===t)return"backspace";if(""===t)return"shift+tab";if(!rt&&"\r"===t)return"alt+enter";if(!rt&&" "===t)return"alt+space";if(""===t||"\b"===t)return"alt+backspace";if(!rt&&"B"===t)return"alt+left";if(!rt&&"F"===t)return"alt+right";if(!rt&&2===t.length&&""===t[0]){const e=t.charCodeAt(1);if(e>=1&&e<=26)return`ctrl+alt+${String.fromCharCode(e+96)}`;if(e>=97&&e<=122||e>=48&&e<=57)return`alt+${String.fromCharCode(e)}`}if(""===t)return"up";if(""===t)return"down";if(""===t)return"right";if(""===t)return"left";if(""===t||"OH"===t)return"home";if(""===t||"OF"===t)return"end";if("[3~"===t)return"delete";if("[5~"===t)return"pageUp";if("[6~"===t)return"pageDown";if(1===t.length){const e=t.charCodeAt(0);if(e>=1&&e<=26)return`ctrl+${String.fromCharCode(e+96)}`;if(e>=32&&e<=126)return t}}const Wt=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Ot=ct.shift|ut;function Et(t){const e=t.match(Wt);if(!e)return;const s=Number.parseInt(e[1]??"",10);if(!Number.isFinite(s))return;const i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,n=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(n)?n-1:0;if(0!==(r&~Ot))return;if(r&(ct.alt|ct.ctrl))return;let o=s;if(r&ct.shift&&"number"==typeof i&&(o=i),Number.isFinite(o)&&!(o<32))try{return String.fromCodePoint(o)}catch{return}}const Ft={cursorUp:"up",cursorDown:"down",cursorLeft:["left","ctrl+b"],cursorRight:["right","ctrl+f"],cursorWordLeft:["alt+left","ctrl+left","alt+b"],cursorWordRight:["alt+right","ctrl+right","alt+f"],cursorLineStart:["home","ctrl+a"],cursorLineEnd:["end","ctrl+e"],jumpForward:"ctrl+]",jumpBackward:"ctrl+alt+]",pageUp:"pageUp",pageDown:"pageDown",deleteCharBackward:"backspace",deleteCharForward:["delete","ctrl+d"],deleteWordBackward:["ctrl+w","alt+backspace"],deleteWordForward:["alt+d","alt+delete"],deleteToLineStart:"ctrl+u",deleteToLineEnd:"ctrl+k",newLine:"shift+enter",submit:"enter",tab:"tab",selectUp:"up",selectDown:"down",selectPageUp:"pageUp",selectPageDown:"pageDown",selectConfirm:"enter",selectCancel:["escape","ctrl+c"],copy:"ctrl+c",yank:"ctrl+y",yankPop:"alt+y",undo:"ctrl+-",expandTools:"ctrl+o",treeFoldOrUp:["ctrl+left","alt+left"],treeUnfoldOrDown:["ctrl+right","alt+right"],toggleSessionPath:"ctrl+p",toggleSessionSort:"ctrl+s",renameSession:"ctrl+r",deleteSession:"ctrl+d",deleteSessionNoninvasive:"ctrl+backspace"};class _t{actionToKeys;constructor(t={}){this.actionToKeys=new Map,this.buildMaps(t)}buildMaps(t){this.actionToKeys.clear();for(const[t,e]of Object.entries(Ft)){const s=Array.isArray(e)?e:[e];this.actionToKeys.set(t,[...s])}for(const[e,s]of Object.entries(t)){if(void 0===s)continue;const t=Array.isArray(s)?s:[s];this.actionToKeys.set(e,t)}}matches(t,e){const s=this.actionToKeys.get(e);if(!s)return!1;for(const e of s)if(Pt(t,e))return!0;return!1}getKeys(t){return this.actionToKeys.get(t)??[]}setConfig(t){this.buildMaps(t)}}let Dt=null;function zt(){return Dt||(Dt=new _t),Dt}function Ut(t){Dt=t}class Vt{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(t="",e=1,s=1,i){this.text=t,this.paddingX=e,this.paddingY=s,this.customBgFn=i}setText(t){this.text=t,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(t){this.customBgFn=t,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(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;if(!this.text||""===this.text.trim()){const e=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=e,e}const e=N(this.text.replace(/\t/g," "),Math.max(1,t-2*this.paddingX)),s=" ".repeat(this.paddingX),i=" ".repeat(this.paddingX),n=[];for(const r of e){const e=s+r+i;if(this.customBgFn)n.push(J(e,t,this.customBgFn));else{const s=H(e),i=Math.max(0,t-s);n.push(e+" ".repeat(i))}}const r=" ".repeat(t),o=[];for(let e=0;e<this.paddingY;e++){const e=this.customBgFn?J(r,t,this.customBgFn):r;o.push(e)}const l=[...o,...n,...o];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=l,l.length>0?l:[""]}}class Ht extends Vt{spinnerColorFn;messageColorFn;message;frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];currentFrame=0;intervalId=null;ui=null;constructor(t,e,s,i="Loading..."){super("",1,0),this.spinnerColorFn=e,this.messageColorFn=s,this.message=i,this.ui=t,this.start()}render(t){return["",...super.render(t)]}start(){this.updateDisplay(),this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},80)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setMessage(t){this.message=t,this.updateDisplay()}updateDisplay(){const t=this.frames[this.currentFrame];this.setText(`${this.spinnerColorFn(t)} ${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}}class qt extends Ht{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(t){zt().matches(t,"selectCancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}}class jt{ring=[];push(t,e){if(t)if(e.accumulate&&this.ring.length>0){const s=this.ring.pop();this.ring.push(e.prepend?t+s:s+t)}else this.ring.push(t)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){const t=this.ring.pop();this.ring.unshift(t)}}get length(){return this.ring.length}}var Kt=s(73024),Nt=s(48161),Gt=s(76760);let Xt=null,Qt={widthPx:9,heightPx:18};function Zt(){return Qt}function Yt(t){Qt=t}function Jt(){const t=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERM?.toLowerCase()||"",s=process.env.COLORTERM?.toLowerCase()||"";if(process.env.KITTY_WINDOW_ID||"kitty"===t)return{images:"kitty",trueColor:!0,hyperlinks:!0};if("ghostty"===t||e.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR)return{images:"kitty",trueColor:!0,hyperlinks:!0};if(process.env.WEZTERM_PANE||"wezterm"===t)return{images:"kitty",trueColor:!0,hyperlinks:!0};if(process.env.ITERM_SESSION_ID||"iterm.app"===t)return{images:"iterm2",trueColor:!0,hyperlinks:!0};if("vscode"===t)return{images:null,trueColor:!0,hyperlinks:!0};if("alacritty"===t)return{images:null,trueColor:!0,hyperlinks:!0};return{images:null,trueColor:"truecolor"===s||"24bit"===s,hyperlinks:!0}}function te(){return Xt||(Xt=Jt()),Xt}function ee(){Xt=null}const se="]1337;File=";function ie(t){return!(!t.startsWith("_G")&&!t.startsWith(se))||(t.includes("_G")||t.includes(se))}function ne(){return Math.floor(4294967294*Math.random())+1}function re(t,e={}){const s=4096,i=["a=T","f=100","q=2"];if(e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),t.length<=s)return`_G${i.join(",")};${t}\\`;const n=[];let r=0,o=!0;for(;r<t.length;){const e=t.slice(r,r+s),l=r+s>=t.length;o?(n.push(`_G${i.join(",")},m=1;${e}\\`),o=!1):l?n.push(`_Gm=0;${e}\\`):n.push(`_Gm=1;${e}\\`),r+=s}return n.join("")}function oe(t){return`_Ga=d,d=I,i=${t}\\`}function le(){return"_Ga=d,d=A\\"}function he(t,e={}){const s=["inline="+(!1!==e.inline?1:0)];if(void 0!==e.width&&s.push(`width=${e.width}`),void 0!==e.height&&s.push(`height=${e.height}`),e.name){const t=Buffer.from(e.name).toString("base64");s.push(`name=${t}`)}return!1===e.preserveAspectRatio&&s.push("preserveAspectRatio=0"),`]1337;File=${s.join(";")}:${t}`}function ae(t,e,s={widthPx:9,heightPx:18}){const i=e*s.widthPx/t.widthPx,n=t.heightPx*i,r=Math.ceil(n/s.heightPx);return Math.max(1,r)}function ce(t){try{const e=Buffer.from(t,"base64");if(e.length<24)return null;if(137!==e[0]||80!==e[1]||78!==e[2]||71!==e[3])return null;const s=e.readUInt32BE(16);return{widthPx:s,heightPx:e.readUInt32BE(20)}}catch{return null}}function ue(t){try{const e=Buffer.from(t,"base64");if(e.length<2)return null;if(255!==e[0]||216!==e[1])return null;let s=2;for(;s<e.length-9;){if(255!==e[s]){s++;continue}const t=e[s+1];if(t>=192&&t<=194){const t=e.readUInt16BE(s+5);return{widthPx:e.readUInt16BE(s+7),heightPx:t}}if(s+3>=e.length)return null;const i=e.readUInt16BE(s+2);if(i<2)return null;s+=2+i}return null}catch{return null}}function de(t){try{const e=Buffer.from(t,"base64");if(e.length<10)return null;const s=e.slice(0,6).toString("ascii");if("GIF87a"!==s&&"GIF89a"!==s)return null;const i=e.readUInt16LE(6);return{widthPx:i,heightPx:e.readUInt16LE(8)}}catch{return null}}function pe(t){try{const e=Buffer.from(t,"base64");if(e.length<30)return null;const s=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if("RIFF"!==s||"WEBP"!==i)return null;const n=e.slice(12,16).toString("ascii");if("VP8 "===n){if(e.length<30)return null;const t=16383&e.readUInt16LE(26);return{widthPx:t,heightPx:16383&e.readUInt16LE(28)}}if("VP8L"===n){if(e.length<25)return null;const t=e.readUInt32LE(21);return{widthPx:1+(16383&t),heightPx:1+(t>>14&16383)}}if("VP8X"===n){if(e.length<30)return null;const t=1+(e[24]|e[25]<<8|e[26]<<16);return{widthPx:t,heightPx:1+(e[27]|e[28]<<8|e[29]<<16)}}return null}catch{return null}}function fe(t,e){return"image/png"===e?ce(t):"image/jpeg"===e?ue(t):"image/gif"===e?de(t):"image/webp"===e?pe(t):null}function ge(t,e,s={}){const i=te();if(!i.images)return null;const n=s.maxWidthCells??80,r=ae(e,n,Zt());if("kitty"===i.images){return{sequence:re(t,{columns:n,rows:r,imageId:s.imageId}),rows:r,imageId:s.imageId}}if("iterm2"===i.images){return{sequence:he(t,{width:n,height:"auto",preserveAspectRatio:s.preserveAspectRatio??!0}),rows:r}}return null}function me(t,e,s){const i=[];return s&&i.push(s),i.push(`[${t}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}function xe(t){return null!==t&&"focused"in t}const ke="_pi:c";function be(t,e){if(void 0===t)return;if("number"==typeof t)return t;const s=t.match(/^(\d+(?:\.\d+)?)%$/);return s?Math.floor(e*parseFloat(s[1])/100):void 0}class Ce{children=[];addChild(t){this.children.push(t)}removeChild(t){const e=this.children.indexOf(t);-1!==e&&this.children.splice(e,1)}clear(){this.children=[]}invalidate(){for(const t of this.children)t.invalidate?.()}render(t){const e=[];for(const s of this.children)e.push(...s.render(t));return e}}class we extends Ce{terminal;previousLines=[];previousWidth=0;previousHeight=0;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;cursorRow=0;hardwareCursorRow=0;inputBuffer="";cellSizeQueryPending=!1;showHardwareCursor="1"===process.env.PI_HARDWARE_CURSOR;clearOnShrink="1"===process.env.PI_CLEAR_ON_SHRINK;maxLinesRendered=0;previousViewportTop=0;fullRedrawCount=0;stopped=!1;focusOrderCounter=0;overlayStack=[];constructor(t,e){super(),this.terminal=t,void 0!==e&&(this.showHardwareCursor=e)}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(t){this.showHardwareCursor!==t&&(this.showHardwareCursor=t,t||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(t){this.clearOnShrink=t}setFocus(t){xe(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=t,xe(t)&&(t.focused=!0)}showOverlay(t,e){const s={component:t,options:e,preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(s),!e?.nonCapturing&&this.isOverlayVisible(s)&&this.setFocus(t),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{const e=this.overlayStack.indexOf(s);if(-1!==e){if(this.overlayStack.splice(e,1),this.focusedComponent===t){const t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??s.preFocus)}0===this.overlayStack.length&&this.terminal.hideCursor(),this.requestRender()}},setHidden:i=>{if(s.hidden!==i){if(s.hidden=i,i){if(this.focusedComponent===t){const t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??s.preFocus)}}else!e?.nonCapturing&&this.isOverlayVisible(s)&&(s.focusOrder=++this.focusOrderCounter,this.setFocus(t));this.requestRender()}},isHidden:()=>s.hidden,focus:()=>{this.overlayStack.includes(s)&&this.isOverlayVisible(s)&&(this.focusedComponent!==t&&this.setFocus(t),s.focusOrder=++this.focusOrderCounter,this.requestRender())},unfocus:()=>{if(this.focusedComponent!==t)return;const e=this.getTopmostVisibleOverlay();this.setFocus(e&&e!==s?e.component:s.preFocus),this.requestRender()},isFocused:()=>this.focusedComponent===t}}hideOverlay(){const t=this.overlayStack.pop();if(t){if(this.focusedComponent===t.component){const e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??t.preFocus)}0===this.overlayStack.length&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(t=>this.isOverlayVisible(t))}isOverlayVisible(t){return!t.hidden&&(!t.options?.visible||t.options.visible(this.terminal.columns,this.terminal.rows))}getTopmostVisibleOverlay(){for(let t=this.overlayStack.length-1;t>=0;t--)if(!this.overlayStack[t].options?.nonCapturing&&this.isOverlayVisible(this.overlayStack[t]))return this.overlayStack[t]}invalidate(){super.invalidate();for(const t of this.overlayStack)t.component.invalidate?.()}start(){this.stopped=!1,this.terminal.start(t=>this.handleInput(t),()=>this.requestRender()),this.terminal.hideCursor(),this.queryCellSize(),this.requestRender()}addInputListener(t){return this.inputListeners.add(t),()=>{this.inputListeners.delete(t)}}removeInputListener(t){this.inputListeners.delete(t)}queryCellSize(){te().images&&(this.cellSizeQueryPending=!0,this.terminal.write(""))}stop(){if(this.stopped=!0,this.previousLines.length>0){const t=this.previousLines.length-this.hardwareCursorRow;t>0?this.terminal.write(`[${t}B`):t<0&&this.terminal.write(`[${-t}A`),this.terminal.write("\r\n")}this.terminal.showCursor(),this.terminal.stop()}requestRender(t=!1){t&&(this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0),this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>{this.renderRequested=!1,this.doRender()}))}handleInput(t){if(this.inputListeners.size>0){let e=t;for(const t of this.inputListeners){const s=t(e);if(s?.consume)return;void 0!==s?.data&&(e=s.data)}if(0===e.length)return;t=e}if(this.cellSizeQueryPending){this.inputBuffer+=t;const e=this.parseCellSizeResponse();if(0===e.length)return;t=e}if(Pt(t,"shift+ctrl+d")&&this.onDebug)return void this.onDebug();const e=this.overlayStack.find(t=>t.component===this.focusedComponent);if(e&&!this.isOverlayVisible(e)){const t=this.getTopmostVisibleOverlay();t?this.setFocus(t.component):this.setFocus(e.preFocus)}if(this.focusedComponent?.handleInput){if(vt(t)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(t),this.requestRender()}}parseCellSizeResponse(){const t=/\x1b\[6;(\d+);(\d+)t/,e=this.inputBuffer.match(t);if(e){const s=parseInt(e[1],10),i=parseInt(e[2],10);s>0&&i>0&&(Yt({widthPx:i,heightPx:s}),this.invalidate(),this.requestRender()),this.inputBuffer=this.inputBuffer.replace(t,""),this.cellSizeQueryPending=!1}if(/\x1b(\[6?;?[\d;]*)?$/.test(this.inputBuffer)){const t=this.inputBuffer[this.inputBuffer.length-1];if(!/[a-zA-Z~]/.test(t))return""}const s=this.inputBuffer;return this.inputBuffer="",this.cellSizeQueryPending=!1,s}resolveOverlayLayout(t,e,s,i){const n=t??{},r="number"==typeof n.margin?{top:n.margin,right:n.margin,bottom:n.margin,left:n.margin}:n.margin??{},o=Math.max(0,r.top??0),l=Math.max(0,r.right??0),h=Math.max(0,r.bottom??0),a=Math.max(0,r.left??0),c=Math.max(1,s-a-l),u=Math.max(1,i-o-h);let d=be(n.width,s)??Math.min(80,c);void 0!==n.minWidth&&(d=Math.max(d,n.minWidth)),d=Math.max(1,Math.min(d,c));let p=be(n.maxHeight,i);void 0!==p&&(p=Math.max(1,Math.min(p,u)));const f=void 0!==p?Math.min(e,p):e;let g,m;if(void 0!==n.row)if("string"==typeof n.row){const t=n.row.match(/^(\d+(?:\.\d+)?)%$/);if(t){const e=Math.max(0,u-f),s=parseFloat(t[1])/100;g=o+Math.floor(e*s)}else g=this.resolveAnchorRow("center",f,u,o)}else g=n.row;else{const t=n.anchor??"center";g=this.resolveAnchorRow(t,f,u,o)}if(void 0!==n.col)if("string"==typeof n.col){const t=n.col.match(/^(\d+(?:\.\d+)?)%$/);if(t){const e=Math.max(0,c-d),s=parseFloat(t[1])/100;m=a+Math.floor(e*s)}else m=this.resolveAnchorCol("center",d,c,a)}else m=n.col;else{const t=n.anchor??"center";m=this.resolveAnchorCol(t,d,c,a)}return void 0!==n.offsetY&&(g+=n.offsetY),void 0!==n.offsetX&&(m+=n.offsetX),g=Math.max(o,Math.min(g,i-h-f)),m=Math.max(a,Math.min(m,s-l-d)),{width:d,row:g,col:m,maxHeight:p}}resolveAnchorRow(t,e,s,i){switch(t){case"top-left":case"top-center":case"top-right":return i;case"bottom-left":case"bottom-center":case"bottom-right":return i+s-e;case"left-center":case"center":case"right-center":return i+Math.floor((s-e)/2)}}resolveAnchorCol(t,e,s,i){switch(t){case"top-left":case"left-center":case"bottom-left":return i;case"top-right":case"right-center":case"bottom-right":return i+s-e;case"top-center":case"center":case"bottom-center":return i+Math.floor((s-e)/2)}}compositeOverlays(t,e,s){if(0===this.overlayStack.length)return t;const i=[...t],n=[];let r=i.length;const o=this.overlayStack.filter(t=>this.isOverlayVisible(t));o.sort((t,e)=>t.focusOrder-e.focusOrder);for(const t of o){const{component:i,options:o}=t,{width:l,maxHeight:h}=this.resolveOverlayLayout(o,0,e,s);let a=i.render(l);void 0!==h&&a.length>h&&(a=a.slice(0,h));const{row:c,col:u}=this.resolveOverlayLayout(o,a.length,e,s);n.push({overlayLines:a,row:c,col:u,w:l}),r=Math.max(r,c+a.length)}const l=Math.max(this.maxLinesRendered,r);for(;i.length<l;)i.push("");const h=Math.max(0,l-s);for(const{overlayLines:t,row:s,col:r,w:o}of n)for(let n=0;n<t.length;n++){const l=h+s+n;if(l>=0&&l<i.length){const s=H(t[n])>o?et(t[n],0,o,!0):t[n];i[l]=this.compositeLineAt(i[l],s,r,o,e)}}return i}static SEGMENT_RESET="]8;;";applyLineResets(t){const e=we.SEGMENT_RESET;for(let s=0;s<t.length;s++){const i=t[s];ie(i)||(t[s]=i+e)}return t}compositeLineAt(t,e,s,i,n){if(ie(t))return t;const r=s+i,o=function(t,e,s,i,n=!1){let r="",o=0,l="",h=0,a=0,c=0,u="",d=!1;const p=s+i;for(it.clear();c<t.length;){const f=q(t,c);if(f){it.process(f.code),a<e?u+=f.code:a>=s&&a<p&&d&&(l+=f.code),c+=f.length;continue}let g=c;for(;g<t.length&&!q(t,g);)g++;for(const{segment:f}of O.segment(t.slice(c,g))){const t=V(f);if(a<e?(u&&(r+=u,u=""),r+=f,o+=t):a>=s&&a<p&&(!n||a+t<=p)&&(d||(l+=it.getActiveCodes(),d=!0),l+=f,h+=t),a+=t,i<=0?a>=e:a>=p)break}if(c=g,i<=0?a>=e:a>=p)break}return{before:r,beforeWidth:o,after:l,afterWidth:h}}(t,s,r,n-r,!0),l=st(e,0,i,!0),h=Math.max(0,s-o.beforeWidth),a=Math.max(0,i-l.width),c=Math.max(s,o.beforeWidth),u=Math.max(i,l.width),d=Math.max(0,n-c-u),p=Math.max(0,d-o.afterWidth),f=we.SEGMENT_RESET,g=o.before+" ".repeat(h)+f+l.text+" ".repeat(a)+f+o.after+" ".repeat(p);return H(g)<=n?g:et(g,0,n,!0)}extractCursorPosition(t,e){const s=Math.max(0,t.length-e);for(let e=t.length-1;e>=s;e--){const s=t[e],i=s.indexOf(ke);if(-1!==i){const n=H(s.slice(0,i));return t[e]=s.slice(0,i)+s.slice(i+ke.length),{row:e,col:n}}}return null}doRender(){if(this.stopped)return;const t=this.terminal.columns,e=this.terminal.rows;let s=Math.max(0,this.maxLinesRendered-e),i=this.previousViewportTop,n=this.hardwareCursorRow;const r=t=>t-s-(n-i);let o=this.render(t);this.overlayStack.length>0&&(o=this.compositeOverlays(o,t,e));const l=this.extractCursorPosition(o,e);o=this.applyLineResets(o);const h=0!==this.previousWidth&&this.previousWidth!==t,a=0!==this.previousHeight&&this.previousHeight!==e,c=s=>{this.fullRedrawCount+=1;let i="[?2026h";s&&(i+="");for(let t=0;t<o.length;t++)t>0&&(i+="\r\n"),i+=o[t];i+="[?2026l",this.terminal.write(i),this.cursorRow=Math.max(0,o.length-1),this.hardwareCursorRow=this.cursorRow,this.maxLinesRendered=s?o.length:Math.max(this.maxLinesRendered,o.length),this.previousViewportTop=Math.max(0,this.maxLinesRendered-e),this.positionHardwareCursor(l,o.length),this.previousLines=o,this.previousWidth=t,this.previousHeight=e},u="1"===process.env.PI_DEBUG_REDRAW,d=t=>{if(!u)return;const s=Gt.join(Nt.homedir(),".pi","agent","pi-debug.log"),i=`[${(new Date).toISOString()}] fullRender: ${t} (prev=${this.previousLines.length}, new=${o.length}, height=${e})\n`;Kt.appendFileSync(s,i)};if(0===this.previousLines.length&&!h&&!a)return d("first render"),void c(!1);if(h||a)return d(`terminal size changed (${this.previousWidth}x${this.previousHeight} -> ${t}x${e})`),void c(!0);if(this.clearOnShrink&&o.length<this.maxLinesRendered&&0===this.overlayStack.length)return d(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),void c(!0);let p=-1,f=-1;const g=Math.max(o.length,this.previousLines.length);for(let t=0;t<g;t++){(t<this.previousLines.length?this.previousLines[t]:"")!==(t<o.length?o[t]:"")&&(-1===p&&(p=t),f=t)}const m=o.length>this.previousLines.length;m&&(-1===p&&(p=this.previousLines.length),f=o.length-1);const x=m&&p===this.previousLines.length&&p>0;if(-1===p)return this.positionHardwareCursor(l,o.length),this.previousViewportTop=Math.max(0,this.maxLinesRendered-e),void(this.previousHeight=e);if(p>=o.length){if(this.previousLines.length>o.length){let t="[?2026h";const s=Math.max(0,o.length-1),i=r(s);i>0?t+=`[${i}B`:i<0&&(t+=`[${-i}A`),t+="\r";const n=this.previousLines.length-o.length;if(n>e)return d(`extraLines > height (${n} > ${e})`),void c(!0);n>0&&(t+="");for(let e=0;e<n;e++)t+="\r",e<n-1&&(t+="");n>0&&(t+=`[${n}A`),t+="[?2026l",this.terminal.write(t),this.cursorRow=s,this.hardwareCursorRow=s}return this.positionHardwareCursor(l,o.length),this.previousLines=o,this.previousWidth=t,this.previousHeight=e,void(this.previousViewportTop=Math.max(0,this.maxLinesRendered-e))}const k=Math.max(0,this.previousLines.length-e);if(p<k)return d(`firstChanged < viewportTop (${p} < ${k})`),void c(!0);let b="[?2026h";const C=i+e-1,w=x?p-1:p;if(w>C){const t=Math.max(0,Math.min(e-1,n-i)),r=e-1-t;r>0&&(b+=`[${r}B`);const o=w-C;b+="\r\n".repeat(o),i+=o,s+=o,n=w}const v=r(w);v>0?b+=`[${v}B`:v<0&&(b+=`[${-v}A`),b+=x?"\r\n":"\r";const y=Math.min(f,o.length-1);for(let e=p;e<=y;e++){e>p&&(b+="\r\n"),b+="";const s=o[e];if(!ie(s)&&H(s)>t){const i=Gt.join(Nt.homedir(),".pi","agent","pi-crash.log"),n=[`Crash at ${(new Date).toISOString()}`,`Terminal width: ${t}`,`Line ${e} visible width: ${H(s)}`,"","=== All rendered lines ===",...o.map((t,e)=>`[${e}] (w=${H(t)}) ${t}`),""].join("\n");Kt.mkdirSync(Gt.dirname(i),{recursive:!0}),Kt.writeFileSync(i,n),this.stop();const r=[`Rendered line ${e} exceeds terminal width (${H(s)} > ${t}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${i}`].join("\n");throw new Error(r)}b+=s}let L=y;if(this.previousLines.length>o.length){if(y<o.length-1){b+=`[${o.length-1-y}B`,L=o.length-1}const t=this.previousLines.length-o.length;for(let t=o.length;t<this.previousLines.length;t++)b+="\r\n";b+=`[${t}A`}if(b+="[?2026l","1"===process.env.PI_TUI_DEBUG){const t="/tmp/tui";Kt.mkdirSync(t,{recursive:!0});const i=Gt.join(t,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),r=[`firstChanged: ${p}`,`viewportTop: ${s}`,`cursorRow: ${this.cursorRow}`,`height: ${e}`,`lineDiff: ${v}`,`hardwareCursorRow: ${n}`,`renderEnd: ${y}`,`finalCursorRow: ${L}`,`cursorPos: ${JSON.stringify(l)}`,`newLines.length: ${o.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(o,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(b)].join("\n");Kt.writeFileSync(i,r)}this.terminal.write(b),this.cursorRow=Math.max(0,o.length-1),this.hardwareCursorRow=L,this.maxLinesRendered=Math.max(this.maxLinesRendered,o.length),this.previousViewportTop=Math.max(0,this.maxLinesRendered-e),this.positionHardwareCursor(l,o.length),this.previousLines=o,this.previousWidth=t,this.previousHeight=e}positionHardwareCursor(t,e){if(!t||e<=0)return void this.terminal.hideCursor();const s=Math.max(0,Math.min(t.row,e-1)),i=Math.max(0,t.col),n=s-this.hardwareCursorRow;let r="";n>0?r+=`[${n}B`:n<0&&(r+=`[${-n}A`),r+=`[${i+1}G`,r&&this.terminal.write(r),this.hardwareCursorRow=s,this.showHardwareCursor?this.terminal.showCursor():this.terminal.hideCursor()}}class ve{stack=[];push(t){this.stack.push(structuredClone(t))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}}const ye=t=>t.replace(/[\r\n]+/g," ").trim();class Le{items=[];filteredItems=[];selectedIndex=0;maxVisible=5;theme;onSelect;onCancel;onSelectionChange;constructor(t,e,s){this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=s}setFilter(t){this.filteredItems=this.items.filter(e=>e.value.toLowerCase().startsWith(t.toLowerCase())),this.selectedIndex=0}setSelectedIndex(t){this.selectedIndex=Math.max(0,Math.min(t,this.filteredItems.length-1))}invalidate(){}render(t){const e=[];if(0===this.filteredItems.length)return e.push(this.theme.noMatch(" No matching commands")),e;const s=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),i=Math.min(s+this.maxVisible,this.filteredItems.length);for(let n=s;n<i;n++){const s=this.filteredItems[n];if(!s)continue;const i=n===this.selectedIndex,r=s.description?ye(s.description):void 0;let o="";if(i){const e=2,i=s.label||s.value;if(r&&t>40){const s=tt(i,Math.min(30,t-e-4),""),n=" ".repeat(Math.max(1,32-s.length)),l=t-(e+s.length+n.length)-2;if(l>10){const t=tt(r,l,"");o=this.theme.selectedText(`→ ${s}${n}${t}`)}else{const s=t-e-2;o=this.theme.selectedText(`→ ${tt(i,s,"")}`)}}else{const s=t-e-2;o=this.theme.selectedText(`→ ${tt(i,s,"")}`)}}else{const e=s.label||s.value,i=" ";if(r&&t>40){const s=tt(e,Math.min(30,t-i.length-4),""),n=" ".repeat(Math.max(1,32-s.length)),l=t-(i.length+s.length+n.length)-2;if(l>10){const t=tt(r,l,"");o=i+s+this.theme.description(n+t)}else{o=i+tt(e,t-i.length-2,"")}}else{o=i+tt(e,t-i.length-2,"")}}e.push(o)}if(s>0||i<this.filteredItems.length){const s=` (${this.selectedIndex+1}/${this.filteredItems.length})`;e.push(this.theme.scrollInfo(tt(s,t-2,"")))}return e}handleInput(t){const e=zt();if(e.matches(t,"selectUp"))this.selectedIndex=0===this.selectedIndex?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(e.matches(t,"selectDown"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(e.matches(t,"selectConfirm")){const t=this.filteredItems[this.selectedIndex];t&&this.onSelect&&this.onSelect(t)}else e.matches(t,"selectCancel")&&this.onCancel&&this.onCancel()}notifySelectionChange(){const t=this.filteredItems[this.selectedIndex];t&&this.onSelectionChange&&this.onSelectionChange(t)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}}const Se=E();function $e(t,e){if(!t||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(H(t)<=e)return[{text:t,startIndex:0,endIndex:t.length}];const s=[],i=[...Se.segment(t)];let n=0,r=0,o=-1,l=0;for(let h=0;h<i.length;h++){const a=i[h],c=a.segment,u=H(c),d=a.index,p=Q(c);n+u>e&&(o>=0?(s.push({text:t.slice(r,o),startIndex:r,endIndex:o}),r=o,n-=l):r<d&&(s.push({text:t.slice(r,d),startIndex:r,endIndex:d}),r=d,n=0),o=-1),n+=u;const f=i[h+1];p&&f&&!Q(f.segment)&&(o=f.index,l=n)}return s.push({text:t.slice(r),startIndex:r,endIndex:t.length}),s}class Ie{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;scrollOffset=0;borderColor;autocompleteProvider;autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;killRing=new jt;lastAction=null;jumpMode=null;preferredVisualCol=null;undoStack=new ve;onSubmit;onChange;disableSubmit=!1;constructor(t,e,s={}){this.tui=t,this.theme=e,this.borderColor=e.borderColor;const i=s.paddingX??0;this.paddingX=Number.isFinite(i)?Math.max(0,Math.floor(i)):0;const n=s.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(n)?Math.max(3,Math.min(20,Math.floor(n))):5}getPaddingX(){return this.paddingX}setPaddingX(t){const e=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;this.paddingX!==e&&(this.paddingX=e,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(t){const e=Number.isFinite(t)?Math.max(3,Math.min(20,Math.floor(t))):5;this.autocompleteMaxVisible!==e&&(this.autocompleteMaxVisible=e,this.tui.requestRender())}setAutocompleteProvider(t){this.autocompleteProvider=t}addToHistory(t){const e=t.trim();e&&(this.history.length>0&&this.history[0]===e||(this.history.unshift(e),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return 1===this.state.lines.length&&""===this.state.lines[0]}isOnFirstVisualLine(){const t=this.buildVisualLineMap(this.lastWidth);return 0===this.findCurrentVisualLine(t)}isOnLastVisualLine(){const t=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(t)===t.length-1}navigateHistory(t){if(this.lastAction=null,0===this.history.length)return;const e=this.historyIndex-t;e<-1||e>=this.history.length||(-1===this.historyIndex&&e>=0&&this.pushUndoSnapshot(),this.historyIndex=e,-1===this.historyIndex?this.setTextInternal(""):this.setTextInternal(this.history[this.historyIndex]||""))}setTextInternal(t){const e=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n");this.state.lines=0===e.length?[""]:e,this.state.cursorLine=this.state.lines.length-1,this.setCursorCol(this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}render(t){const e=Math.max(0,Math.floor((t-1)/2)),s=Math.min(this.paddingX,e),i=Math.max(1,t-2*s),n=Math.max(1,i-(s?0:1));this.lastWidth=n;const r=this.borderColor("─"),o=this.layoutText(n),l=this.tui.terminal.rows,h=Math.max(5,Math.floor(.3*l));let a=o.findIndex(t=>t.hasCursor);-1===a&&(a=0),a<this.scrollOffset?this.scrollOffset=a:a>=this.scrollOffset+h&&(this.scrollOffset=a-h+1);const c=Math.max(0,o.length-h);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,c));const u=o.slice(this.scrollOffset,this.scrollOffset+h),d=[],p=" ".repeat(s),f=p;if(this.scrollOffset>0){const e=`─── ↑ ${this.scrollOffset} more `,s=t-H(e);d.push(this.borderColor(e+"─".repeat(Math.max(0,s))))}else d.push(r.repeat(t));const g=this.focused&&!this.autocompleteState;for(const t of u){let e=t.text,n=H(t.text),r=!1;if(t.hasCursor&&void 0!==t.cursorPos){const o=e.slice(0,t.cursorPos),l=e.slice(t.cursorPos),h=g?ke:"";if(l.length>0){const t=[...Se.segment(l)],s=t[0]?.segment||"";e=o+h+`${s}`+l.slice(s.length)}else{e=o+h+" ",n+=1,n>i&&s>0&&(r=!0)}}const o=" ".repeat(Math.max(0,i-n)),l=r?f.slice(1):f;d.push(`${p}${e}${o}${l}`)}const m=o.length-(this.scrollOffset+u.length);if(m>0){const e=`─── ↓ ${m} more `,s=t-H(e);d.push(this.borderColor(e+"─".repeat(Math.max(0,s))))}else d.push(r.repeat(t));if(this.autocompleteState&&this.autocompleteList){const t=this.autocompleteList.render(i);for(const e of t){const t=H(e),s=" ".repeat(Math.max(0,i-t));d.push(`${p}${e}${s}${f}`)}}return d}handleInput(t){const e=zt();if(null!==this.jumpMode){if(e.matches(t,"jumpForward")||e.matches(t,"jumpBackward"))return void(this.jumpMode=null);if(t.charCodeAt(0)>=32){const e=this.jumpMode;return this.jumpMode=null,void this.jumpToChar(t,e)}this.jumpMode=null}if(t.includes("[200~")&&(this.isInPaste=!0,this.pasteBuffer="",t=t.replace("[200~","")),this.isInPaste){this.pasteBuffer+=t;const e=this.pasteBuffer.indexOf("[201~");if(-1!==e){const t=this.pasteBuffer.substring(0,e);t.length>0&&this.handlePaste(t),this.isInPaste=!1;const s=this.pasteBuffer.substring(e+6);return this.pasteBuffer="",void(s.length>0&&this.handleInput(s))}return}if(e.matches(t,"copy"))return;if(e.matches(t,"undo"))return void this.undo();if(this.autocompleteState&&this.autocompleteList){if(e.matches(t,"selectCancel"))return void this.cancelAutocomplete();if(e.matches(t,"selectUp")||e.matches(t,"selectDown"))return void this.autocompleteList.handleInput(t);if(e.matches(t,"tab")){const t=this.autocompleteList.getSelectedItem();if(t&&this.autocompleteProvider){const e=this.shouldChainSlashArgumentAutocompleteOnTabSelection();this.pushUndoSnapshot(),this.lastAction=null;const s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,t,this.autocompletePrefix);this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),e&&this.isBareCompletedSlashCommandAtCursor()&&this.tryTriggerAutocomplete()}return}if(e.matches(t,"selectConfirm")){const t=this.autocompleteList.getSelectedItem();if(t&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;const e=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,t,this.autocompletePrefix);if(this.state.lines=e.lines,this.state.cursorLine=e.cursorLine,this.setCursorCol(e.cursorCol),!this.autocompletePrefix.startsWith("/"))return this.cancelAutocomplete(),void(this.onChange&&this.onChange(this.getText()));this.cancelAutocomplete()}}}if(e.matches(t,"tab")&&!this.autocompleteState)return void this.handleTabCompletion();if(e.matches(t,"deleteToLineEnd"))return void this.deleteToEndOfLine();if(e.matches(t,"deleteToLineStart"))return void this.deleteToStartOfLine();if(e.matches(t,"deleteWordBackward"))return void this.deleteWordBackwards();if(e.matches(t,"deleteWordForward"))return void this.deleteWordForward();if(e.matches(t,"deleteCharBackward")||Pt(t,"shift+backspace"))return void this.handleBackspace();if(e.matches(t,"deleteCharForward")||Pt(t,"shift+delete"))return void this.handleForwardDelete();if(e.matches(t,"yank"))return void this.yank();if(e.matches(t,"yankPop"))return void this.yankPop();if(e.matches(t,"cursorLineStart"))return void this.moveToLineStart();if(e.matches(t,"cursorLineEnd"))return void this.moveToLineEnd();if(e.matches(t,"cursorWordLeft"))return void this.moveWordBackwards();if(e.matches(t,"cursorWordRight"))return void this.moveWordForwards();if(e.matches(t,"newLine")||10===t.charCodeAt(0)&&t.length>1||"\r"===t||"[13;2~"===t||t.length>1&&t.includes("")&&t.includes("\r")||"\n"===t&&1===t.length)return this.shouldSubmitOnBackslashEnter(t,e)?(this.handleBackspace(),void this.submitValue()):void this.addNewLine();if(e.matches(t,"submit")){if(this.disableSubmit)return;const t=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&"\\"===t[this.state.cursorCol-1]?(this.handleBackspace(),void this.addNewLine()):void this.submitValue()}if(e.matches(t,"cursorUp"))return void(this.isEditorEmpty()||this.historyIndex>-1&&this.isOnFirstVisualLine()?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0));if(e.matches(t,"cursorDown"))return void(this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0));if(e.matches(t,"cursorRight"))return void this.moveCursor(0,1);if(e.matches(t,"cursorLeft"))return void this.moveCursor(0,-1);if(e.matches(t,"pageUp"))return void this.pageScroll(-1);if(e.matches(t,"pageDown"))return void this.pageScroll(1);if(e.matches(t,"jumpForward"))return void(this.jumpMode="forward");if(e.matches(t,"jumpBackward"))return void(this.jumpMode="backward");if(Pt(t,"shift+space"))return void this.insertCharacter(" ");const s=Et(t);void 0===s?t.charCodeAt(0)>=32&&this.insertCharacter(t):this.insertCharacter(s)}layoutText(t){const e=[];if(0===this.state.lines.length||1===this.state.lines.length&&""===this.state.lines[0])return e.push({text:"",hasCursor:!0,cursorPos:0}),e;for(let s=0;s<this.state.lines.length;s++){const i=this.state.lines[s]||"",n=s===this.state.cursorLine;if(H(i)<=t)n?e.push({text:i,hasCursor:!0,cursorPos:this.state.cursorCol}):e.push({text:i,hasCursor:!1});else{const s=$e(i,t);for(let t=0;t<s.length;t++){const i=s[t];if(!i)continue;const r=this.state.cursorCol,o=t===s.length-1;let l=!1,h=0;n&&(o?(l=r>=i.startIndex,h=r-i.startIndex):(l=r>=i.startIndex&&r<i.endIndex,l&&(h=r-i.startIndex,h>i.text.length&&(h=i.text.length)))),l?e.push({text:i.text,hasCursor:!0,cursorPos:h}):e.push({text:i.text,hasCursor:!1})}}}return e}getText(){return this.state.lines.join("\n")}getExpandedText(){let t=this.state.lines.join("\n");for(const[e,s]of this.pastes){const i=new RegExp(`\\[paste #${e}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(i,s)}return t}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(t){this.lastAction=null,this.historyIndex=-1,this.getText()!==t&&this.pushUndoSnapshot(),this.setTextInternal(t)}insertTextAtCursor(t){t&&(this.pushUndoSnapshot(),this.lastAction=null,this.historyIndex=-1,this.insertTextAtCursorInternal(t))}insertTextAtCursorInternal(t){if(!t)return;const e=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s=e.split("\n"),i=this.state.lines[this.state.cursorLine]||"",n=i.slice(0,this.state.cursorCol),r=i.slice(this.state.cursorCol);1===s.length?(this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),n+s[0],...s.slice(1,-1),s[s.length-1]+r,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=s.length-1,this.setCursorCol((s[s.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(t,e){this.historyIndex=-1,e||((Q(t)||"type-word"!==this.lastAction)&&this.pushUndoSnapshot(),this.lastAction="type-word");const s=this.state.lines[this.state.cursorLine]||"",i=s.slice(0,this.state.cursorCol),n=s.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=i+t+n,this.setCursorCol(this.state.cursorCol+t.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if("/"===t&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if("@"===t){const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol),e=t[t.length-2];1!==t.length&&" "!==e&&"\t"!==e||this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(t)){const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);(this.isInSlashCommandContext(t)||t.match(/(?:^|[\s])@[^\s]*$/))&&this.tryTriggerAutocomplete()}}handlePaste(t){this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();let e=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\t/g," ").split("").filter(t=>"\n"===t||t.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(e)){const t=this.state.lines[this.state.cursorLine]||"",s=this.state.cursorCol>0?t[this.state.cursorCol-1]:"";s&&/\w/.test(s)&&(e=` ${e}`)}const s=e.split("\n"),i=e.length;if(s.length>10||i>1e3){this.pasteCounter++;const t=this.pasteCounter;this.pastes.set(t,e);const n=s.length>10?`[paste #${t} +${s.length} lines]`:`[paste #${t} ${i} chars]`;return void this.insertTextAtCursorInternal(n)}s.length,this.insertTextAtCursorInternal(e)}addNewLine(){this.historyIndex=-1,this.lastAction=null,this.pushUndoSnapshot();const t=this.state.lines[this.state.cursorLine]||"",e=t.slice(0,this.state.cursorCol),s=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=e,this.state.lines.splice(this.state.cursorLine+1,0,s),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(t,e){if(this.disableSubmit)return!1;if(!Pt(t,"enter"))return!1;const s=e.getKeys("submit");if(!(s.includes("shift+enter")||s.includes("shift+return")))return!1;const i=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&"\\"===i[this.state.cursorCol-1]}submitValue(){let t=this.state.lines.join("\n").trim();for(const[e,s]of this.pastes){const i=new RegExp(`\\[paste #${e}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(i,s)}this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.historyIndex=-1,this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(t)}handleBackspace(){if(this.historyIndex=-1,this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();const t=this.state.lines[this.state.cursorLine]||"",e=t.slice(0,this.state.cursorCol),s=[...Se.segment(e)],i=s[s.length-1],n=i?i.segment.length:1,r=t.slice(0,this.state.cursorCol-n),o=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+o,this.setCursorCol(this.state.cursorCol-n)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();const t=this.state.lines[this.state.cursorLine]||"",e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);(this.isInSlashCommandContext(t)||t.match(/(?:^|[\s])@[^\s]*$/))&&this.tryTriggerAutocomplete()}}setCursorCol(t){this.state.cursorCol=t,this.preferredVisualCol=null}moveToVisualLine(t,e,s){const i=t[e],n=t[s];if(i&&n){const r=this.state.cursorCol-i.startCol,o=e===t.length-1||t[e+1]?.logicalLine!==i.logicalLine?i.length:Math.max(0,i.length-1),l=s===t.length-1||t[s+1]?.logicalLine!==n.logicalLine?n.length:Math.max(0,n.length-1),h=this.computeVerticalMoveColumn(r,o,l);this.state.cursorLine=n.logicalLine;const a=n.startCol+h,c=this.state.lines[n.logicalLine]||"";this.state.cursorCol=Math.min(a,c.length)}}computeVerticalMoveColumn(t,e,s){const i=s<t;if(!(null!==this.preferredVisualCol)||t<e)return i?(this.preferredVisualCol=t,s):(this.preferredVisualCol=null,t);const n=s<this.preferredVisualCol;if(i||n)return s;const r=this.preferredVisualCol;return this.preferredVisualCol=null,r}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;const t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}deleteToStartOfLine(){this.historyIndex=-1;const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();const e=t.slice(0,this.state.cursorCol);this.killRing.push(e,{prepend:!0,accumulate:"kill"===this.lastAction}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push("\n",{prepend:!0,accumulate:"kill"===this.lastAction}),this.lastAction="kill";const e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.historyIndex=-1;const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<t.length){this.pushUndoSnapshot();const e=t.slice(this.state.cursorCol);this.killRing.push(e,{prepend:!1,accumulate:"kill"===this.lastAction}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push("\n",{prepend:!1,accumulate:"kill"===this.lastAction}),this.lastAction="kill";const e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.historyIndex=-1;const t=this.state.lines[this.state.cursorLine]||"";if(0===this.state.cursorCol){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push("\n",{prepend:!0,accumulate:"kill"===this.lastAction}),this.lastAction="kill";const e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length)}}else{this.pushUndoSnapshot();const e="kill"===this.lastAction,s=this.state.cursorCol;this.moveWordBackwards();const i=this.state.cursorCol;this.setCursorCol(s);const n=t.slice(i,this.state.cursorCol);this.killRing.push(n,{prepend:!0,accumulate:e}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,i)+t.slice(this.state.cursorCol),this.setCursorCol(i)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.historyIndex=-1;const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=t.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push("\n",{prepend:!1,accumulate:"kill"===this.lastAction}),this.lastAction="kill";const e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();const e="kill"===this.lastAction,s=this.state.cursorCol;this.moveWordForwards();const i=this.state.cursorCol;this.setCursorCol(s);const n=t.slice(this.state.cursorCol,i);this.killRing.push(n,{prepend:!1,accumulate:e}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,this.state.cursorCol)+t.slice(i)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.historyIndex=-1,this.lastAction=null;const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<t.length){this.pushUndoSnapshot();const e=t.slice(this.state.cursorCol),s=[...Se.segment(e)][0],i=s?s.segment.length:1,n=t.slice(0,this.state.cursorCol),r=t.slice(this.state.cursorCol+i);this.state.lines[this.state.cursorLine]=n+r}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();const e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);(this.isInSlashCommandContext(t)||t.match(/(?:^|[\s])@[^\s]*$/))&&this.tryTriggerAutocomplete()}}buildVisualLineMap(t){const e=[];for(let s=0;s<this.state.lines.length;s++){const i=this.state.lines[s]||"",n=H(i);if(0===i.length)e.push({logicalLine:s,startCol:0,length:0});else if(n<=t)e.push({logicalLine:s,startCol:0,length:i.length});else{const n=$e(i,t);for(const t of n)e.push({logicalLine:s,startCol:t.startIndex,length:t.endIndex-t.startIndex})}}return e}findCurrentVisualLine(t){for(let e=0;e<t.length;e++){const s=t[e];if(s&&s.logicalLine===this.state.cursorLine){const i=this.state.cursorCol-s.startCol,n=e===t.length-1||t[e+1]?.logicalLine!==s.logicalLine;if(i>=0&&(i<s.length||n&&i<=s.length))return e}}return t.length-1}moveCursor(t,e){this.lastAction=null;const s=this.buildVisualLineMap(this.lastWidth),i=this.findCurrentVisualLine(s);if(0!==t){const e=i+t;e>=0&&e<s.length&&this.moveToVisualLine(s,i,e)}if(0!==e){const t=this.state.lines[this.state.cursorLine]||"";if(e>0)if(this.state.cursorCol<t.length){const e=t.slice(this.state.cursorCol),s=[...Se.segment(e)][0];this.setCursorCol(this.state.cursorCol+(s?s.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{const t=s[i];t&&(this.preferredVisualCol=this.state.cursorCol-t.startCol)}else if(this.state.cursorCol>0){const e=t.slice(0,this.state.cursorCol),s=[...Se.segment(e)],i=s[s.length-1];this.setCursorCol(this.state.cursorCol-(i?i.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;const t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}}}pageScroll(t){this.lastAction=null;const e=this.tui.terminal.rows,s=Math.max(5,Math.floor(.3*e)),i=this.buildVisualLineMap(this.lastWidth),n=this.findCurrentVisualLine(i),r=Math.max(0,Math.min(i.length-1,n+t*s));this.moveToVisualLine(i,n,r)}moveWordBackwards(){this.lastAction=null;const t=this.state.lines[this.state.cursorLine]||"";if(0===this.state.cursorCol){if(this.state.cursorLine>0){this.state.cursorLine--;const t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}return}const e=t.slice(0,this.state.cursorCol),s=[...Se.segment(e)];let i=this.state.cursorCol;for(;s.length>0&&Q(s[s.length-1]?.segment||"");)i-=s.pop()?.segment.length||0;if(s.length>0){if(Z(s[s.length-1]?.segment||""))for(;s.length>0&&Z(s[s.length-1]?.segment||"");)i-=s.pop()?.segment.length||0;else for(;s.length>0&&!Q(s[s.length-1]?.segment||"")&&!Z(s[s.length-1]?.segment||"");)i-=s.pop()?.segment.length||0}this.setCursorCol(i)}yank(){if(0===this.killRing.length)return;this.pushUndoSnapshot();const t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank"}yankPop(){if("yank"!==this.lastAction||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();const t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank"}insertYankedText(t){this.historyIndex=-1;const e=t.split("\n");if(1===e.length){const e=this.state.lines[this.state.cursorLine]||"",s=e.slice(0,this.state.cursorCol),i=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+t+i,this.setCursorCol(this.state.cursorCol+t.length)}else{const t=this.state.lines[this.state.cursorLine]||"",s=t.slice(0,this.state.cursorCol),i=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+(e[0]||"");for(let t=1;t<e.length-1;t++)this.state.lines.splice(this.state.cursorLine+t,0,e[t]||"");const n=this.state.cursorLine+e.length-1;this.state.lines.splice(n,0,(e[e.length-1]||"")+i),this.state.cursorLine=n,this.setCursorCol((e[e.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){const t=this.killRing.peek();if(!t)return;const e=t.split("\n");if(1===e.length){const e=this.state.lines[this.state.cursorLine]||"",s=t.length,i=e.slice(0,this.state.cursorCol-s),n=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=i+n,this.setCursorCol(this.state.cursorCol-s)}else{const t=this.state.cursorLine-(e.length-1),s=(this.state.lines[t]||"").length-(e[0]||"").length,i=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),n=(this.state.lines[t]||"").slice(0,s);this.state.lines.splice(t,e.length,n+i),this.state.cursorLine=t,this.setCursorCol(s)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push(this.state)}undo(){this.historyIndex=-1;const t=this.undoStack.pop();t&&(Object.assign(this.state,t),this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(t,e){this.lastAction=null;const s="forward"===e,i=this.state.lines,n=s?i.length:-1,r=s?1:-1;for(let e=this.state.cursorLine;e!==n;e+=r){const n=i[e]||"",r=e===this.state.cursorLine?s?this.state.cursorCol+1:this.state.cursorCol-1:void 0,o=s?n.indexOf(t,r):n.lastIndexOf(t,r);if(-1!==o)return this.state.cursorLine=e,void this.setCursorCol(o)}}moveWordForwards(){this.lastAction=null;const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=t.length)return void(this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0)));const e=t.slice(this.state.cursorCol),s=Se.segment(e)[Symbol.iterator]();let i=s.next(),n=this.state.cursorCol;for(;!i.done&&Q(i.value.segment);)n+=i.value.segment.length,i=s.next();if(!i.done){if(Z(i.value.segment))for(;!i.done&&Z(i.value.segment);)n+=i.value.segment.length,i=s.next();else for(;!i.done&&!Q(i.value.segment)&&!Z(i.value.segment);)n+=i.value.segment.length,i=s.next()}this.setCursorCol(n)}isSlashMenuAllowed(){return 0===this.state.cursorLine}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return""===t.trim()||"/"===t.trim()}isInSlashCommandContext(t){return this.isSlashMenuAllowed()&&t.trimStart().startsWith("/")}shouldChainSlashArgumentAutocompleteOnTabSelection(){if("regular"!==this.autocompleteState)return!1;const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.isInSlashCommandContext(t)&&!t.trimStart().includes(" ")}isBareCompletedSlashCommandAtCursor(){const t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol!==t.length)return!1;const e=t.slice(0,this.state.cursorCol).trimStart();return/^\/\S+ $/.test(e)}getBestAutocompleteMatchIndex(t,e){if(!e)return-1;let s=-1;for(let i=0;i<t.length;i++){const n=t[i].value;if(n===e)return i;-1===s&&n.startsWith(e)&&(s=i)}return s}tryTriggerAutocomplete(t=!1){if(!this.autocompleteProvider)return;if(t){const t=this.autocompleteProvider;if(!(!t.shouldTriggerFileCompletion||t.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return}const e=this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol);if(e&&e.items.length>0){this.autocompletePrefix=e.prefix,this.autocompleteList=new Le(e.items,this.autocompleteMaxVisible,this.theme.selectList);const t=this.getBestAutocompleteMatchIndex(e.items,e.prefix);t>=0&&this.autocompleteList.setSelectedIndex(t),this.autocompleteState="regular"}else this.cancelAutocomplete()}handleTabCompletion(){if(!this.autocompleteProvider)return;const t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)&&!t.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.tryTriggerAutocomplete(!0)}forceFileAutocomplete(t=!1){if(!this.autocompleteProvider)return;const e=this.autocompleteProvider;if("function"!=typeof e.getForceFileSuggestions)return void this.tryTriggerAutocomplete(!0);const s=e.getForceFileSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol);if(s&&s.items.length>0){if(t&&1===s.items.length){const t=s.items[0];this.pushUndoSnapshot(),this.lastAction=null;const e=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,t,s.prefix);return this.state.lines=e.lines,this.state.cursorLine=e.cursorLine,this.setCursorCol(e.cursorCol),void(this.onChange&&this.onChange(this.getText()))}this.autocompletePrefix=s.prefix,this.autocompleteList=new Le(s.items,this.autocompleteMaxVisible,this.theme.selectList);const e=this.getBestAutocompleteMatchIndex(s.items,s.prefix);e>=0&&this.autocompleteList.setSelectedIndex(e),this.autocompleteState="force"}else this.cancelAutocomplete()}cancelAutocomplete(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}isShowingAutocomplete(){return null!==this.autocompleteState}updateAutocomplete(){if(!this.autocompleteState||!this.autocompleteProvider)return;if("force"===this.autocompleteState)return void this.forceFileAutocomplete();const t=this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol);if(t&&t.items.length>0){this.autocompletePrefix=t.prefix,this.autocompleteList=new Le(t.items,this.autocompleteMaxVisible,this.theme.selectList);const e=this.getBestAutocompleteMatchIndex(t.items,t.prefix);e>=0&&this.autocompleteList.setSelectedIndex(e)}else this.cancelAutocomplete()}}class Te{base64Data;mimeType;dimensions;theme;options;imageId;cachedLines;cachedWidth;constructor(t,e,s,i={},n){this.base64Data=t,this.mimeType=e,this.theme=s,this.options=i,this.dimensions=n||fe(t,e)||{widthPx:800,heightPx:600},this.imageId=i.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(t){if(this.cachedLines&&this.cachedWidth===t)return this.cachedLines;const e=Math.min(t-2,this.options.maxWidthCells??60);let s;if(te().images){const t=ge(this.base64Data,this.dimensions,{maxWidthCells:e,imageId:this.imageId});if(t){t.imageId&&(this.imageId=t.imageId),s=[];for(let e=0;e<t.rows-1;e++)s.push("");const e=t.rows>1?`[${t.rows-1}A`:"";s.push(e+t.sequence)}else{const t=me(this.mimeType,this.dimensions,this.options.filename);s=[this.theme.fallbackColor(t)]}}else{const t=me(this.mimeType,this.dimensions,this.options.filename);s=[this.theme.fallbackColor(t)]}return this.cachedLines=s,this.cachedWidth=t,s}}const Ae=E();class Re{value="";cursor=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new jt;lastAction=null;undoStack=new ve;getValue(){return this.value}setValue(t){this.value=t,this.cursor=Math.min(this.cursor,t.length)}handleInput(t){if(t.includes("[200~")&&(this.isInPaste=!0,this.pasteBuffer="",t=t.replace("[200~","")),this.isInPaste){this.pasteBuffer+=t;const e=this.pasteBuffer.indexOf("[201~");if(-1!==e){const t=this.pasteBuffer.substring(0,e);this.handlePaste(t),this.isInPaste=!1;const s=this.pasteBuffer.substring(e+6);this.pasteBuffer="",s&&this.handleInput(s)}return}const e=zt();if(e.matches(t,"selectCancel"))return void(this.onEscape&&this.onEscape());if(e.matches(t,"undo"))return void this.undo();if(e.matches(t,"submit")||"\n"===t)return void(this.onSubmit&&this.onSubmit(this.value));if(e.matches(t,"deleteCharBackward"))return void this.handleBackspace();if(e.matches(t,"deleteCharForward"))return void this.handleForwardDelete();if(e.matches(t,"deleteWordBackward"))return void this.deleteWordBackwards();if(e.matches(t,"deleteWordForward"))return void this.deleteWordForward();if(e.matches(t,"deleteToLineStart"))return void this.deleteToLineStart();if(e.matches(t,"deleteToLineEnd"))return void this.deleteToLineEnd();if(e.matches(t,"yank"))return void this.yank();if(e.matches(t,"yankPop"))return void this.yankPop();if(e.matches(t,"cursorLeft")){if(this.lastAction=null,this.cursor>0){const t=this.value.slice(0,this.cursor),e=[...Ae.segment(t)],s=e[e.length-1];this.cursor-=s?s.segment.length:1}return}if(e.matches(t,"cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){const t=this.value.slice(this.cursor),e=[...Ae.segment(t)][0];this.cursor+=e?e.segment.length:1}return}if(e.matches(t,"cursorLineStart"))return this.lastAction=null,void(this.cursor=0);if(e.matches(t,"cursorLineEnd"))return this.lastAction=null,void(this.cursor=this.value.length);if(e.matches(t,"cursorWordLeft"))return void this.moveWordBackwards();if(e.matches(t,"cursorWordRight"))return void this.moveWordForwards();const s=Et(t);if(void 0!==s)return void this.insertCharacter(s);[...t].some(t=>{const e=t.charCodeAt(0);return e<32||127===e||e>=128&&e<=159})||this.insertCharacter(t)}insertCharacter(t){(Q(t)||"type-word"!==this.lastAction)&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();const t=this.value.slice(0,this.cursor),e=[...Ae.segment(t)],s=e[e.length-1],i=s?s.segment.length:1;this.value=this.value.slice(0,this.cursor-i)+this.value.slice(this.cursor),this.cursor-=i}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();const t=this.value.slice(this.cursor),e=[...Ae.segment(t)][0],s=e?e.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+s)}}deleteToLineStart(){if(0===this.cursor)return;this.pushUndo();const t=this.value.slice(0,this.cursor);this.killRing.push(t,{prepend:!0,accumulate:"kill"===this.lastAction}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();const t=this.value.slice(this.cursor);this.killRing.push(t,{prepend:!1,accumulate:"kill"===this.lastAction}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(0===this.cursor)return;const t="kill"===this.lastAction;this.pushUndo();const e=this.cursor;this.moveWordBackwards();const s=this.cursor;this.cursor=e;const i=this.value.slice(s,this.cursor);this.killRing.push(i,{prepend:!0,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,s)+this.value.slice(this.cursor),this.cursor=s}deleteWordForward(){if(this.cursor>=this.value.length)return;const t="kill"===this.lastAction;this.pushUndo();const e=this.cursor;this.moveWordForwards();const s=this.cursor;this.cursor=e;const i=this.value.slice(this.cursor,s);this.killRing.push(i,{prepend:!1,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(s)}yank(){const t=this.killRing.peek();t&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank")}yankPop(){if("yank"!==this.lastAction||this.killRing.length<=1)return;this.pushUndo();const t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-t.length)+this.value.slice(this.cursor),this.cursor-=t.length,this.killRing.rotate();const e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){const t=this.undoStack.pop();t&&(this.value=t.value,this.cursor=t.cursor,this.lastAction=null)}moveWordBackwards(){if(0===this.cursor)return;this.lastAction=null;const t=this.value.slice(0,this.cursor),e=[...Ae.segment(t)];for(;e.length>0&&Q(e[e.length-1]?.segment||"");)this.cursor-=e.pop()?.segment.length||0;if(e.length>0){if(Z(e[e.length-1]?.segment||""))for(;e.length>0&&Z(e[e.length-1]?.segment||"");)this.cursor-=e.pop()?.segment.length||0;else for(;e.length>0&&!Q(e[e.length-1]?.segment||"")&&!Z(e[e.length-1]?.segment||"");)this.cursor-=e.pop()?.segment.length||0}}moveWordForwards(){if(this.cursor>=this.value.length)return;this.lastAction=null;const t=this.value.slice(this.cursor),e=Ae.segment(t)[Symbol.iterator]();let s=e.next();for(;!s.done&&Q(s.value.segment);)this.cursor+=s.value.segment.length,s=e.next();if(!s.done){if(Z(s.value.segment))for(;!s.done&&Z(s.value.segment);)this.cursor+=s.value.segment.length,s=e.next();else for(;!s.done&&!Q(s.value.segment)&&!Z(s.value.segment);)this.cursor+=s.value.segment.length,s=e.next()}}handlePaste(t){this.lastAction=null,this.pushUndo();const e=t.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"");this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}invalidate(){}render(t){const e="> ",s=t-2;if(s<=0)return[e];let i="",n=this.cursor;if(this.value.length<s)i=this.value;else{const t=this.cursor===this.value.length?s-1:s,e=Math.floor(t/2),r=t=>{for(;t<this.value.length;){const e=this.value.charCodeAt(t);if(!(e>=56320&&e<57344))break;t++}return t},o=t=>{for(;t>0;){const e=this.value.charCodeAt(t-1);if(!(e>=55296&&e<56320))break;t--}return t};if(this.cursor<e)i=this.value.slice(0,o(t)),n=this.cursor;else if(this.cursor>this.value.length-e){const e=r(this.value.length-t);i=this.value.slice(e),n=this.cursor-e}else{const s=r(this.cursor-e);i=this.value.slice(s,o(s+t)),n=e}}const r=[...Ae.segment(i.slice(n))][0],o=i.slice(0,n),l=r?.segment??" ",h=i.slice(n+l.length),a=o+(this.focused?ke:"")+`${l}`+h,c=H(a);return[e+a+" ".repeat(Math.max(0,s-c))]}}function Pe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Me={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function Be(t){Me=t}var We={exec:()=>null};function Oe(t,e=""){let s="string"==typeof t?t:t.source;const i={replace:(t,e)=>{let n="string"==typeof e?e:e.source;return n=n.replace(Ee.caret,"$1"),s=s.replace(t,n),i},getRegex:()=>new RegExp(s,e)};return i}var Ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},Fe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_e=/(?:[*+-]|\d{1,9}[.)])/,De=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ze=Oe(De).replace(/bull/g,_e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ue=Oe(De).replace(/bull/g,_e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ve=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,He=/(?!\s*\])(?:\\.|[^\[\]\\])+/,qe=Oe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",He).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),je=Oe(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,_e).getRegex(),Ke="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",Ne=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ge=Oe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Ne).replace("tag",Ke).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xe=Oe(Ve).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ke).getRegex(),Qe={blockquote:Oe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xe).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:qe,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:Fe,html:Ge,lheading:ze,list:je,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:Xe,table:We,text:/^[^\n]+/},Ze=Oe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ke).getRegex(),Ye={...Qe,lheading:Ue,table:Ze,paragraph:Oe(Ve).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ze).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ke).getRegex()},Je={...Qe,html:Oe("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",Ne).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:We,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Oe(Ve).replace("hr",Fe).replace("heading"," *#{1,6} *[^\n]").replace("lheading",ze).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ts=/^( {2,}|\\)\n(?!\s*$)/,es=/[\p{P}\p{S}]/u,ss=/[\s\p{P}\p{S}]/u,is=/[^\s\p{P}\p{S}]/u,ns=Oe(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ss).getRegex(),rs=/(?!~)[\p{P}\p{S}]/u,os=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ls=Oe(os,"u").replace(/punct/g,es).getRegex(),hs=Oe(os,"u").replace(/punct/g,rs).getRegex(),as="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",cs=Oe(as,"gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,ss).replace(/punct/g,es).getRegex(),us=Oe(as,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,rs).getRegex(),ds=Oe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,ss).replace(/punct/g,es).getRegex(),ps=Oe(/\\(punct)/,"gu").replace(/punct/g,es).getRegex(),fs=Oe(/^<(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(),gs=Oe(Ne).replace("(?:--\x3e|$)","--\x3e").getRegex(),ms=Oe("^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",gs).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xs=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ks=Oe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",xs).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),bs=Oe(/^!?\[(label)\]\[(ref)\]/).replace("label",xs).replace("ref",He).getRegex(),Cs=Oe(/^!?\[(ref)\](?:\[\])?/).replace("ref",He).getRegex(),ws={_backpedal:We,anyPunctuation:ps,autolink:fs,blockSkip:/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,br:ts,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:We,emStrongLDelim:ls,emStrongRDelimAst:cs,emStrongRDelimUnd:ds,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:ks,nolink:Cs,punctuation:ns,reflink:bs,reflinkSearch:Oe("reflink|nolink(?!\\()","g").replace("reflink",bs).replace("nolink",Cs).getRegex(),tag:ms,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:We},vs={...ws,link:Oe(/^!?\[(label)\]\((.*?)\)/).replace("label",xs).getRegex(),reflink:Oe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",xs).getRegex()},ys={...ws,emStrongRDelimAst:us,emStrongLDelim:hs,url:Oe(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Ls={...ys,br:Oe(ts).replace("{2,}","*").getRegex(),text:Oe(ys.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ss={normal:Qe,gfm:Ye,pedantic:Je},$s={normal:ws,gfm:ys,breaks:Ls,pedantic:vs},Is={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ts=t=>Is[t];function As(t,e){if(e){if(Ee.escapeTest.test(t))return t.replace(Ee.escapeReplace,Ts)}else if(Ee.escapeTestNoEncode.test(t))return t.replace(Ee.escapeReplaceNoEncode,Ts);return t}function Rs(t){try{t=encodeURI(t).replace(Ee.percentDecode,"%")}catch{return null}return t}function Ps(t,e){const s=t.replace(Ee.findPipe,(t,e,s)=>{let i=!1,n=e;for(;--n>=0&&"\\"===s[n];)i=!i;return i?"|":" |"}).split(Ee.splitPipe);let i=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;i<s.length;i++)s[i]=s[i].trim().replace(Ee.slashPipe,"|");return s}function Ms(t,e,s){const i=t.length;if(0===i)return"";let n=0;for(;n<i;){const r=t.charAt(i-n-1);if(r!==e||s){if(r===e||!s)break;n++}else n++}return t.slice(0,i-n)}function Bs(t,e,s,i,n){const r=e.href,o=e.title||null,l=t[1].replace(n.other.outputLinkReplace,"$1");i.state.inLink=!0;const h={type:"!"===t[0].charAt(0)?"image":"link",raw:s,href:r,title:o,text:l,tokens:i.inlineTokens(l)};return i.state.inLink=!1,h}var Ws=class{options;rules;lexer;constructor(t){this.options=t||Me}space(t){const e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){const e=this.rules.block.code.exec(t);if(e){const t=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:Ms(t,"\n")}}}fences(t){const e=this.rules.block.fences.exec(t);if(e){const t=e[0],s=function(t,e,s){const i=t.match(s.other.indentCodeCompensation);if(null===i)return e;const n=i[1];return e.split("\n").map(t=>{const e=t.match(s.other.beginningSpace);if(null===e)return t;const[i]=e;return i.length>=n.length?t.slice(n.length):t}).join("\n")}(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(t){const e=this.rules.block.heading.exec(t);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){const e=Ms(t,"#");this.options.pedantic?t=e.trim():e&&!this.rules.other.endingSpaceChar.test(e)||(t=e.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(t){const e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Ms(e[0],"\n")}}blockquote(t){const e=this.rules.block.blockquote.exec(t);if(e){let t=Ms(e[0],"\n").split("\n"),s="",i="";const n=[];for(;t.length>0;){let e=!1;const r=[];let o;for(o=0;o<t.length;o++)if(this.rules.other.blockquoteStart.test(t[o]))r.push(t[o]),e=!0;else{if(e)break;r.push(t[o])}t=t.slice(o);const l=r.join("\n"),h=l.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}\n${l}`:l,i=i?`${i}\n${h}`:h;const a=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,n,!0),this.lexer.state.top=a,0===t.length)break;const c=n.at(-1);if("code"===c?.type)break;if("blockquote"===c?.type){const e=c,r=e.raw+"\n"+t.join("\n"),o=this.blockquote(r);n[n.length-1]=o,s=s.substring(0,s.length-e.raw.length)+o.raw,i=i.substring(0,i.length-e.text.length)+o.text;break}if("list"===c?.type){const e=c,r=e.raw+"\n"+t.join("\n"),o=this.list(r);n[n.length-1]=o,s=s.substring(0,s.length-c.raw.length)+o.raw,i=i.substring(0,i.length-e.raw.length)+o.raw,t=r.substring(n.at(-1).raw.length).split("\n");continue}}return{type:"blockquote",raw:s,tokens:n,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let s=e[1].trim();const i=s.length>1,n={type:"list",raw:"",ordered:i,start:i?+s.slice(0,-1):"",loose:!1,items:[]};s=i?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=i?s:"[*+-]");const r=this.rules.other.listItemRegex(s);let o=!1;for(;t;){let s=!1,i="",l="";if(!(e=r.exec(t)))break;if(this.rules.block.hr.test(t))break;i=e[0],t=t.substring(i.length);let h=e[2].split("\n",1)[0].replace(this.rules.other.listReplaceTabs,t=>" ".repeat(3*t.length)),a=t.split("\n",1)[0],c=!h.trim(),u=0;if(this.options.pedantic?(u=2,l=h.trimStart()):c?u=e[1].length+1:(u=e[2].search(this.rules.other.nonSpaceChar),u=u>4?1:u,l=h.slice(u),u+=e[1].length),c&&this.rules.other.blankLine.test(a)&&(i+=a+"\n",t=t.substring(a.length+1),s=!0),!s){const e=this.rules.other.nextBulletRegex(u),s=this.rules.other.hrRegex(u),n=this.rules.other.fencesBeginRegex(u),r=this.rules.other.headingBeginRegex(u),o=this.rules.other.htmlBeginRegex(u);for(;t;){const d=t.split("\n",1)[0];let p;if(a=d,this.options.pedantic?(a=a.replace(this.rules.other.listReplaceNesting," "),p=a):p=a.replace(this.rules.other.tabCharGlobal," "),n.test(a))break;if(r.test(a))break;if(o.test(a))break;if(e.test(a))break;if(s.test(a))break;if(p.search(this.rules.other.nonSpaceChar)>=u||!a.trim())l+="\n"+p.slice(u);else{if(c)break;if(h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4)break;if(n.test(h))break;if(r.test(h))break;if(s.test(h))break;l+="\n"+a}c||a.trim()||(c=!0),i+=d+"\n",t=t.substring(d.length+1),h=p.slice(u)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(i)&&(o=!0));let d,p=null;this.options.gfm&&(p=this.rules.other.listIsTask.exec(l),p&&(d="[ ] "!==p[0],l=l.replace(this.rules.other.listReplaceTask,""))),n.items.push({type:"list_item",raw:i,task:!!p,checked:d,loose:!1,text:l,tokens:[]}),n.raw+=i}const l=n.items.at(-1);if(!l)return;l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd(),n.raw=n.raw.trimEnd();for(let t=0;t<n.items.length;t++)if(this.lexer.state.top=!1,n.items[t].tokens=this.lexer.blockTokens(n.items[t].text,[]),!n.loose){const e=n.items[t].tokens.filter(t=>"space"===t.type),s=e.length>0&&e.some(t=>this.rules.other.anyLine.test(t.raw));n.loose=s}if(n.loose)for(let t=0;t<n.items.length;t++)n.items[t].loose=!0;return n}}html(t){const e=this.rules.block.html.exec(t);if(e){return{type:"html",block:!0,raw:e[0],pre:"pre"===e[1]||"script"===e[1]||"style"===e[1],text:e[0]}}}def(t){const e=this.rules.block.def.exec(t);if(e){const t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:s,title:i}}}table(t){const e=this.rules.block.table.exec(t);if(!e)return;if(!this.rules.other.tableDelimiter.test(e[2]))return;const s=Ps(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],r={type:"table",raw:e[0],header:[],align:[],rows:[]};if(s.length===i.length){for(const t of i)this.rules.other.tableAlignRight.test(t)?r.align.push("right"):this.rules.other.tableAlignCenter.test(t)?r.align.push("center"):this.rules.other.tableAlignLeft.test(t)?r.align.push("left"):r.align.push(null);for(let t=0;t<s.length;t++)r.header.push({text:s[t],tokens:this.lexer.inline(s[t]),header:!0,align:r.align[t]});for(const t of n)r.rows.push(Ps(t,r.header.length).map((t,e)=>({text:t,tokens:this.lexer.inline(t),header:!1,align:r.align[e]})));return r}}lheading(t){const e=this.rules.block.lheading.exec(t);if(e)return{type:"heading",raw:e[0],depth:"="===e[2].charAt(0)?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(t){const e=this.rules.block.paragraph.exec(t);if(e){const t="\n"===e[1].charAt(e[1].length-1)?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(t){const e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){const e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){const e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){const e=this.rules.inline.link.exec(t);if(e){const t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;const e=Ms(t.slice(0,-1),"\\");if((t.length-e.length)%2==0)return}else{const t=function(t,e){if(-1===t.indexOf(e[1]))return-1;let s=0;for(let i=0;i<t.length;i++)if("\\"===t[i])i++;else if(t[i]===e[0])s++;else if(t[i]===e[1]&&(s--,s<0))return i;return s>0?-2:-1}(e[2],"()");if(-2===t)return;if(t>-1){const s=(0===e[0].indexOf("!")?5:4)+e[1].length+t;e[2]=e[2].substring(0,t),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let s=e[2],i="";if(this.options.pedantic){const t=this.rules.other.pedanticHrefTitle.exec(s);t&&(s=t[1],i=t[3])}else i=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(s=this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?s.slice(1):s.slice(1,-1)),Bs(e,{href:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s,title:i?i.replace(this.rules.inline.anyPunctuation,"$1"):i},e[0],this.lexer,this.rules)}}reflink(t,e){let s;if((s=this.rules.inline.reflink.exec(t))||(s=this.rules.inline.nolink.exec(t))){const t=e[(s[2]||s[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!t){const t=s[0].charAt(0);return{type:"text",raw:t,text:t}}return Bs(s,t,s[0],this.lexer,this.rules)}}emStrong(t,e,s=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!i)return;if(i[3]&&s.match(this.rules.other.unicodeAlphaNumeric))return;if(!(i[1]||i[2]||"")||!s||this.rules.inline.punctuation.exec(s)){const s=[...i[0]].length-1;let n,r,o=s,l=0;const h="*"===i[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(h.lastIndex=0,e=e.slice(-1*t.length+s);null!=(i=h.exec(e));){if(n=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!n)continue;if(r=[...n].length,i[3]||i[4]){o+=r;continue}if((i[5]||i[6])&&s%3&&!((s+r)%3)){l+=r;continue}if(o-=r,o>0)continue;r=Math.min(r,r+o+l);const e=[...i[0]][0].length,h=t.slice(0,s+i.index+e+r);if(Math.min(s,r)%2){const t=h.slice(1,-1);return{type:"em",raw:h,text:t,tokens:this.lexer.inlineTokens(t)}}const a=h.slice(2,-2);return{type:"strong",raw:h,text:a,tokens:this.lexer.inlineTokens(a)}}}}codespan(t){const e=this.rules.inline.code.exec(t);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," ");const s=this.rules.other.nonSpaceChar.test(t),i=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return s&&i&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(t){const e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t){const e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(t){const e=this.rules.inline.autolink.exec(t);if(e){let t,s;return"@"===e[2]?(t=e[1],s="mailto:"+t):(t=e[1],s=t),{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let t,s;if("@"===e[2])t=e[0],s="mailto:"+t;else{let i;do{i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??""}while(i!==e[0]);t=e[0],s="www."===e[1]?"http://"+e[0]:e[0]}return{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(t){const e=this.rules.inline.text.exec(t);if(e){const t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},Os=class t{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Me,this.options.tokenizer=this.options.tokenizer||new Ws,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const e={other:Ee,block:Ss.normal,inline:$s.normal};this.options.pedantic?(e.block=Ss.pedantic,e.inline=$s.pedantic):this.options.gfm&&(e.block=Ss.gfm,this.options.breaks?e.inline=$s.breaks:e.inline=$s.gfm),this.tokenizer.rules=e}static get rules(){return{block:Ss,inline:$s}}static lex(e,s){return new t(s).lex(e)}static lexInline(e,s){return new t(s).inlineTokens(e)}lex(t){t=t.replace(Ee.carriageReturn,"\n"),this.blockTokens(t,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){const e=this.inlineQueue[t];this.inlineTokens(e.src,e.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,e=[],s=!1){for(this.options.pedantic&&(t=t.replace(Ee.tabCharGlobal," ").replace(Ee.spaceLine,""));t;){let i;if(this.options.extensions?.block?.some(s=>!!(i=s.call({lexer:this},t,e))&&(t=t.substring(i.raw.length),e.push(i),!0)))continue;if(i=this.tokenizer.space(t)){t=t.substring(i.raw.length);const s=e.at(-1);1===i.raw.length&&void 0!==s?s.raw+="\n":e.push(i);continue}if(i=this.tokenizer.code(t)){t=t.substring(i.raw.length);const s=e.at(-1);"paragraph"===s?.type||"text"===s?.type?(s.raw+="\n"+i.raw,s.text+="\n"+i.text,this.inlineQueue.at(-1).src=s.text):e.push(i);continue}if(i=this.tokenizer.fences(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.heading(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.hr(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.blockquote(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.list(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.html(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.def(t)){t=t.substring(i.raw.length);const s=e.at(-1);"paragraph"===s?.type||"text"===s?.type?(s.raw+="\n"+i.raw,s.text+="\n"+i.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title});continue}if(i=this.tokenizer.table(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.lheading(t)){t=t.substring(i.raw.length),e.push(i);continue}let n=t;if(this.options.extensions?.startBlock){let e=1/0;const s=t.slice(1);let i;this.options.extensions.startBlock.forEach(t=>{i=t.call({lexer:this},s),"number"==typeof i&&i>=0&&(e=Math.min(e,i))}),e<1/0&&e>=0&&(n=t.substring(0,e+1))}if(this.state.top&&(i=this.tokenizer.paragraph(n))){const r=e.at(-1);s&&"paragraph"===r?.type?(r.raw+="\n"+i.raw,r.text+="\n"+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):e.push(i),s=n.length!==t.length,t=t.substring(i.raw.length);continue}if(i=this.tokenizer.text(t)){t=t.substring(i.raw.length);const s=e.at(-1);"text"===s?.type?(s.raw+="\n"+i.raw,s.text+="\n"+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):e.push(i);continue}if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}return this.state.top=!0,e}inline(t,e=[]){return this.inlineQueue.push({src:t,tokens:e}),e}inlineTokens(t,e=[]){let s=t,i=null;if(this.tokens.links){const t=Object.keys(this.tokens.links);if(t.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(s));)t.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(s));)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(s));)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let n=!1,r="";for(;t;){let i;if(n||(r=""),n=!1,this.options.extensions?.inline?.some(s=>!!(i=s.call({lexer:this},t,e))&&(t=t.substring(i.raw.length),e.push(i),!0)))continue;if(i=this.tokenizer.escape(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.tag(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.link(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(i.raw.length);const s=e.at(-1);"text"===i.type&&"text"===s?.type?(s.raw+=i.raw,s.text+=i.text):e.push(i);continue}if(i=this.tokenizer.emStrong(t,s,r)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.codespan(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.br(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.del(t)){t=t.substring(i.raw.length),e.push(i);continue}if(i=this.tokenizer.autolink(t)){t=t.substring(i.raw.length),e.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(t))){t=t.substring(i.raw.length),e.push(i);continue}let o=t;if(this.options.extensions?.startInline){let e=1/0;const s=t.slice(1);let i;this.options.extensions.startInline.forEach(t=>{i=t.call({lexer:this},s),"number"==typeof i&&i>=0&&(e=Math.min(e,i))}),e<1/0&&e>=0&&(o=t.substring(0,e+1))}if(i=this.tokenizer.inlineText(o)){t=t.substring(i.raw.length),"_"!==i.raw.slice(-1)&&(r=i.raw.slice(-1)),n=!0;const s=e.at(-1);"text"===s?.type?(s.raw+=i.raw,s.text+=i.text):e.push(i);continue}if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}return e}},Es=class{options;parser;constructor(t){this.options=t||Me}space(t){return""}code({text:t,lang:e,escaped:s}){const i=(e||"").match(Ee.notSpaceStart)?.[0],n=t.replace(Ee.endingNewline,"")+"\n";return i?'<pre><code class="language-'+As(i)+'">'+(s?n:As(n,!0))+"</code></pre>\n":"<pre><code>"+(s?n:As(n,!0))+"</code></pre>\n"}blockquote({tokens:t}){return`<blockquote>\n${this.parser.parse(t)}</blockquote>\n`}html({text:t}){return t}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>\n`}hr(t){return"<hr>\n"}list(t){const e=t.ordered,s=t.start;let i="";for(let e=0;e<t.items.length;e++){const s=t.items[e];i+=this.listitem(s)}const n=e?"ol":"ul";return"<"+n+(e&&1!==s?' start="'+s+'"':"")+">\n"+i+"</"+n+">\n"}listitem(t){let e="";if(t.task){const s=this.checkbox({checked:!!t.checked});t.loose?"paragraph"===t.tokens[0]?.type?(t.tokens[0].text=s+" "+t.tokens[0].text,t.tokens[0].tokens&&t.tokens[0].tokens.length>0&&"text"===t.tokens[0].tokens[0].type&&(t.tokens[0].tokens[0].text=s+" "+As(t.tokens[0].tokens[0].text),t.tokens[0].tokens[0].escaped=!0)):t.tokens.unshift({type:"text",raw:s+" ",text:s+" ",escaped:!0}):e+=s+" "}return e+=this.parser.parse(t.tokens,!!t.loose),`<li>${e}</li>\n`}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>\n`}table(t){let e="",s="";for(let e=0;e<t.header.length;e++)s+=this.tablecell(t.header[e]);e+=this.tablerow({text:s});let i="";for(let e=0;e<t.rows.length;e++){const n=t.rows[e];s="";for(let t=0;t<n.length;t++)s+=this.tablecell(n[t]);i+=this.tablerow({text:s})}return i&&(i=`<tbody>${i}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+i+"</table>\n"}tablerow({text:t}){return`<tr>\n${t}</tr>\n`}tablecell(t){const e=this.parser.parseInline(t.tokens),s=t.header?"th":"td";return(t.align?`<${s} align="${t.align}">`:`<${s}>`)+e+`</${s}>\n`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${As(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:s}){const i=this.parser.parseInline(s),n=Rs(t);if(null===n)return i;let r='<a href="'+(t=n)+'"';return e&&(r+=' title="'+As(e)+'"'),r+=">"+i+"</a>",r}image({href:t,title:e,text:s,tokens:i}){i&&(s=this.parser.parseInline(i,this.parser.textRenderer));const n=Rs(t);if(null===n)return As(s);let r=`<img src="${t=n}" alt="${s}"`;return e&&(r+=` title="${As(e)}"`),r+=">",r}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:As(t.text)}},Fs=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}},_s=class t{options;renderer;textRenderer;constructor(t){this.options=t||Me,this.options.renderer=this.options.renderer||new Es,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Fs}static parse(e,s){return new t(s).parse(e)}static parseInline(e,s){return new t(s).parseInline(e)}parse(t,e=!0){let s="";for(let i=0;i<t.length;i++){const n=t[i];if(this.options.extensions?.renderers?.[n.type]){const t=n,e=this.options.extensions.renderers[t.type].call({parser:this},t);if(!1!==e||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(t.type)){s+=e||"";continue}}const r=n;switch(r.type){case"space":s+=this.renderer.space(r);continue;case"hr":s+=this.renderer.hr(r);continue;case"heading":s+=this.renderer.heading(r);continue;case"code":s+=this.renderer.code(r);continue;case"table":s+=this.renderer.table(r);continue;case"blockquote":s+=this.renderer.blockquote(r);continue;case"list":s+=this.renderer.list(r);continue;case"html":s+=this.renderer.html(r);continue;case"paragraph":s+=this.renderer.paragraph(r);continue;case"text":{let n=r,o=this.renderer.text(n);for(;i+1<t.length&&"text"===t[i+1].type;)n=t[++i],o+="\n"+this.renderer.text(n);s+=e?this.renderer.paragraph({type:"paragraph",raw:o,text:o,tokens:[{type:"text",raw:o,text:o,escaped:!0}]}):o;continue}default:{const t='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(t),"";throw new Error(t)}}}return s}parseInline(t,e=this.renderer){let s="";for(let i=0;i<t.length;i++){const n=t[i];if(this.options.extensions?.renderers?.[n.type]){const t=this.options.extensions.renderers[n.type].call({parser:this},n);if(!1!==t||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(n.type)){s+=t||"";continue}}const r=n;switch(r.type){case"escape":case"text":s+=e.text(r);break;case"html":s+=e.html(r);break;case"link":s+=e.link(r);break;case"image":s+=e.image(r);break;case"strong":s+=e.strong(r);break;case"em":s+=e.em(r);break;case"codespan":s+=e.codespan(r);break;case"br":s+=e.br(r);break;case"del":s+=e.del(r);break;default:{const t='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(t),"";throw new Error(t)}}}return s}},Ds=class{options;block;constructor(t){this.options=t||Me}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}provideLexer(){return this.block?Os.lex:Os.lexInline}provideParser(){return this.block?_s.parse:_s.parseInline}},zs=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=_s;Renderer=Es;TextRenderer=Fs;Lexer=Os;Tokenizer=Ws;Hooks=Ds;constructor(...t){this.use(...t)}walkTokens(t,e){let s=[];for(const i of t)switch(s=s.concat(e.call(this,i)),i.type){case"table":{const t=i;for(const i of t.header)s=s.concat(this.walkTokens(i.tokens,e));for(const i of t.rows)for(const t of i)s=s.concat(this.walkTokens(t.tokens,e));break}case"list":{const t=i;s=s.concat(this.walkTokens(t.items,e));break}default:{const t=i;this.defaults.extensions?.childTokens?.[t.type]?this.defaults.extensions.childTokens[t.type].forEach(i=>{const n=t[i].flat(1/0);s=s.concat(this.walkTokens(n,e))}):t.tokens&&(s=s.concat(this.walkTokens(t.tokens,e)))}}return s}use(...t){const e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(t=>{const s={...t};if(s.async=this.defaults.async||s.async||!1,t.extensions&&(t.extensions.forEach(t=>{if(!t.name)throw new Error("extension name required");if("renderer"in t){const s=e.renderers[t.name];e.renderers[t.name]=s?function(...e){let i=t.renderer.apply(this,e);return!1===i&&(i=s.apply(this,e)),i}:t.renderer}if("tokenizer"in t){if(!t.level||"block"!==t.level&&"inline"!==t.level)throw new Error("extension level must be 'block' or 'inline'");const s=e[t.level];s?s.unshift(t.tokenizer):e[t.level]=[t.tokenizer],t.start&&("block"===t.level?e.startBlock?e.startBlock.push(t.start):e.startBlock=[t.start]:"inline"===t.level&&(e.startInline?e.startInline.push(t.start):e.startInline=[t.start]))}"childTokens"in t&&t.childTokens&&(e.childTokens[t.name]=t.childTokens)}),s.extensions=e),t.renderer){const e=this.defaults.renderer||new Es(this.defaults);for(const s in t.renderer){if(!(s in e))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;const i=s,n=t.renderer[i],r=e[i];e[i]=(...t)=>{let s=n.apply(e,t);return!1===s&&(s=r.apply(e,t)),s||""}}s.renderer=e}if(t.tokenizer){const e=this.defaults.tokenizer||new Ws(this.defaults);for(const s in t.tokenizer){if(!(s in e))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;const i=s,n=t.tokenizer[i],r=e[i];e[i]=(...t)=>{let s=n.apply(e,t);return!1===s&&(s=r.apply(e,t)),s}}s.tokenizer=e}if(t.hooks){const e=this.defaults.hooks||new Ds;for(const s in t.hooks){if(!(s in e))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;const i=s,n=t.hooks[i],r=e[i];Ds.passThroughHooks.has(s)?e[i]=t=>{if(this.defaults.async)return Promise.resolve(n.call(e,t)).then(t=>r.call(e,t));const s=n.call(e,t);return r.call(e,s)}:e[i]=(...t)=>{let s=n.apply(e,t);return!1===s&&(s=r.apply(e,t)),s}}s.hooks=e}if(t.walkTokens){const e=this.defaults.walkTokens,i=t.walkTokens;s.walkTokens=function(t){let s=[];return s.push(i.call(this,t)),e&&(s=s.concat(e.call(this,t))),s}}this.defaults={...this.defaults,...s}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Os.lex(t,e??this.defaults)}parser(t,e){return _s.parse(t,e??this.defaults)}parseMarkdown(t){return(e,s)=>{const i={...s},n={...this.defaults,...i},r=this.onError(!!n.silent,!!n.async);if(!0===this.defaults.async&&!1===i.async)return r(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(null==e)return r(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof e)return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));n.hooks&&(n.hooks.options=n,n.hooks.block=t);const o=n.hooks?n.hooks.provideLexer():t?Os.lex:Os.lexInline,l=n.hooks?n.hooks.provideParser():t?_s.parse:_s.parseInline;if(n.async)return Promise.resolve(n.hooks?n.hooks.preprocess(e):e).then(t=>o(t,n)).then(t=>n.hooks?n.hooks.processAllTokens(t):t).then(t=>n.walkTokens?Promise.all(this.walkTokens(t,n.walkTokens)).then(()=>t):t).then(t=>l(t,n)).then(t=>n.hooks?n.hooks.postprocess(t):t).catch(r);try{n.hooks&&(e=n.hooks.preprocess(e));let t=o(e,n);n.hooks&&(t=n.hooks.processAllTokens(t)),n.walkTokens&&this.walkTokens(t,n.walkTokens);let s=l(t,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(t){return r(t)}}}onError(t,e){return s=>{if(s.message+="\nPlease report this to https://github.com/markedjs/marked.",t){const t="<p>An error occurred:</p><pre>"+As(s.message+"",!0)+"</pre>";return e?Promise.resolve(t):t}if(e)return Promise.reject(s);throw s}}};function Us(t,e){return zs.parse(t,e)}Us.options=Us.setOptions=function(t){return zs.setOptions(t),Us.defaults=zs.defaults,Be(Us.defaults),Us},Us.getDefaults=Pe,Us.defaults=Me,Us.use=function(...t){return zs.use(...t),Us.defaults=zs.defaults,Be(Us.defaults),Us},Us.walkTokens=function(t,e){return zs.walkTokens(t,e)},Us.parseInline=zs.parseInline,Us.Parser=_s,Us.parser=_s.parse,Us.Renderer=Es,Us.TextRenderer=Fs,Us.Lexer=Os,Us.lexer=Os.lex,Us.Tokenizer=Ws,Us.Hooks=Ds,Us.parse=Us;Us.options,Us.setOptions,Us.use,Us.walkTokens,Us.parseInline,_s.parse,Os.lex;class Vs{text;paddingX;paddingY;defaultTextStyle;theme;defaultStylePrefix;cachedText;cachedWidth;cachedLines;constructor(t,e,s,i,n){this.text=t,this.paddingX=e,this.paddingY=s,this.theme=i,this.defaultTextStyle=n}setText(t){this.text=t,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;const e=Math.max(1,t-2*this.paddingX);if(!this.text||""===this.text.trim()){const e=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=e,e}const s=this.text.replace(/\t/g," "),i=Us.lexer(s),n=[];for(let t=0;t<i.length;t++){const s=i[t],r=i[t+1],o=this.renderToken(s,e,r?.type);n.push(...o)}const r=[];for(const t of n)ie(t)?r.push(t):r.push(...N(t,e));const o=" ".repeat(this.paddingX),l=" ".repeat(this.paddingX),h=this.defaultTextStyle?.bgColor,a=[];for(const e of r){if(ie(e)){a.push(e);continue}const s=o+e+l;if(h)a.push(J(s,t,h));else{const e=H(s),i=Math.max(0,t-e);a.push(s+" ".repeat(i))}}const c=" ".repeat(t),u=[];for(let e=0;e<this.paddingY;e++){const e=h?J(c,t,h):c;u.push(e)}const d=[...u,...a,...u];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=d,d.length>0?d:[""]}applyDefaultStyle(t){if(!this.defaultTextStyle)return t;let e=t;return this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e)),e}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(void 0!==this.defaultStylePrefix)return this.defaultStylePrefix;let t="\0";this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));const e=t.indexOf("\0");return this.defaultStylePrefix=e>=0?t.slice(0,e):"",this.defaultStylePrefix}getStylePrefix(t){const e=t("\0"),s=e.indexOf("\0");return s>=0?e.slice(0,s):""}getDefaultInlineStyleContext(){return{applyText:t=>this.applyDefaultStyle(t),stylePrefix:this.getDefaultStylePrefix()}}renderToken(t,e,s,i){const n=[];switch(t.type){case"heading":{const e=t.depth,r=`${"#".repeat(e)} `,o=this.renderInlineTokens(t.tokens||[],i);let l;l=1===e?this.theme.heading(this.theme.bold(this.theme.underline(o))):2===e?this.theme.heading(this.theme.bold(o)):this.theme.heading(this.theme.bold(r+o)),n.push(l),"space"!==s&&n.push("");break}case"paragraph":{const e=this.renderInlineTokens(t.tokens||[],i);n.push(e),s&&"list"!==s&&"space"!==s&&n.push("");break}case"code":{const e=this.theme.codeBlockIndent??" ";if(n.push(this.theme.codeBlockBorder(`\`\`\`${t.lang||""}`)),this.theme.highlightCode){const s=this.theme.highlightCode(t.text,t.lang);for(const t of s)n.push(`${e}${t}`)}else{const s=t.text.split("\n");for(const t of s)n.push(`${e}${this.theme.codeBlock(t)}`)}n.push(this.theme.codeBlockBorder("```")),"space"!==s&&n.push("");break}case"list":{const e=this.renderList(t,0,i);n.push(...e);break}case"table":{const s=this.renderTable(t,e,i);n.push(...s);break}case"blockquote":{const i=t=>this.theme.quote(this.theme.italic(t)),r=this.getStylePrefix(i),o=t=>{if(!r)return i(t);const e=t.replace(/\x1b\[0m/g,`${r}`);return i(e)},l=Math.max(1,e-2),h={applyText:t=>t,stylePrefix:""},a=t.tokens||[],c=[];for(let t=0;t<a.length;t++){const e=a[t],s=a[t+1];c.push(...this.renderToken(e,l,s?.type,h))}for(;c.length>0&&""===c[c.length-1];)c.pop();for(const t of c){const e=N(o(t),l);for(const t of e)n.push(this.theme.quoteBorder("│ ")+t)}"space"!==s&&n.push("");break}case"hr":n.push(this.theme.hr("─".repeat(Math.min(e,80)))),"space"!==s&&n.push("");break;case"html":"raw"in t&&"string"==typeof t.raw&&n.push(this.applyDefaultStyle(t.raw.trim()));break;case"space":n.push("");break;default:"text"in t&&"string"==typeof t.text&&n.push(t.text)}return n}renderInlineTokens(t,e){let s="";const i=e??this.getDefaultInlineStyleContext(),{applyText:n,stylePrefix:r}=i,o=t=>t.split("\n").map(t=>n(t)).join("\n");for(const e of t)switch(e.type){case"text":e.tokens&&e.tokens.length>0?s+=this.renderInlineTokens(e.tokens,i):s+=o(e.text);break;case"paragraph":s+=this.renderInlineTokens(e.tokens||[],i);break;case"strong":{const t=this.renderInlineTokens(e.tokens||[],i);s+=this.theme.bold(t)+r;break}case"em":{const t=this.renderInlineTokens(e.tokens||[],i);s+=this.theme.italic(t)+r;break}case"codespan":s+=this.theme.code(e.text)+r;break;case"link":{const t=this.renderInlineTokens(e.tokens||[],i),n=e.href.startsWith("mailto:")?e.href.slice(7):e.href;e.text===e.href||e.text===n?s+=this.theme.link(this.theme.underline(t))+r:s+=this.theme.link(this.theme.underline(t))+this.theme.linkUrl(` (${e.href})`)+r;break}case"br":s+="\n";break;case"del":{const t=this.renderInlineTokens(e.tokens||[],i);s+=this.theme.strikethrough(t)+r;break}case"html":"raw"in e&&"string"==typeof e.raw&&(s+=o(e.raw));break;default:"text"in e&&"string"==typeof e.text&&(s+=o(e.text))}return s}renderList(t,e,s){const i=[],n=" ".repeat(e),r=t.start??1;for(let o=0;o<t.items.length;o++){const l=t.items[o],h=t.ordered?`${r+o}. `:"- ",a=this.renderListItem(l.tokens||[],e,s);if(a.length>0){const t=a[0];/^\s+\x1b\[36m[-\d]/.test(t)?i.push(t):i.push(n+this.theme.listBullet(h)+t);for(let t=1;t<a.length;t++){const e=a[t];/^\s+\x1b\[36m[-\d]/.test(e)?i.push(e):i.push(`${n} ${e}`)}}else i.push(n+this.theme.listBullet(h))}return i}renderListItem(t,e,s){const i=[];for(const n of t)if("list"===n.type){const t=this.renderList(n,e+1,s);i.push(...t)}else if("text"===n.type){const t=n.tokens&&n.tokens.length>0?this.renderInlineTokens(n.tokens,s):n.text||"";i.push(t)}else if("paragraph"===n.type){const t=this.renderInlineTokens(n.tokens||[],s);i.push(t)}else if("code"===n.type){const t=this.theme.codeBlockIndent??" ";if(i.push(this.theme.codeBlockBorder(`\`\`\`${n.lang||""}`)),this.theme.highlightCode){const e=this.theme.highlightCode(n.text,n.lang);for(const s of e)i.push(`${t}${s}`)}else{const e=n.text.split("\n");for(const s of e)i.push(`${t}${this.theme.codeBlock(s)}`)}i.push(this.theme.codeBlockBorder("```"))}else{const t=this.renderInlineTokens([n],s);t&&i.push(t)}return i}getLongestWordWidth(t,e){const s=t.split(/\s+/).filter(t=>t.length>0);let i=0;for(const t of s)i=Math.max(i,H(t));return void 0===e?i:Math.min(i,e)}wrapCellText(t,e){return N(t,Math.max(1,e))}renderTable(t,e,s){const i=[],n=t.header.length;if(0===n)return i;const r=3*n+1,o=e-r;if(o<n){const s=t.raw?N(t.raw,e):[];return s.push(""),s}const l=[],h=[];for(let e=0;e<n;e++){const i=this.renderInlineTokens(t.header[e].tokens||[],s);l[e]=H(i),h[e]=Math.max(1,this.getLongestWordWidth(i,30))}for(const e of t.rows)for(let t=0;t<e.length;t++){const i=this.renderInlineTokens(e[t].tokens||[],s);l[t]=Math.max(l[t]||0,H(i)),h[t]=Math.max(h[t]||1,this.getLongestWordWidth(i,30))}let a=h,c=a.reduce((t,e)=>t+e,0);if(c>o){a=new Array(n).fill(1);const t=o-n;if(t>0){const e=h.reduce((t,e)=>t+Math.max(0,e-1),0),s=h.map(s=>{const i=Math.max(0,s-1);return e>0?Math.floor(i/e*t):0});for(let t=0;t<n;t++)a[t]+=s[t]??0;const i=s.reduce((t,e)=>t+e,0);let r=t-i;for(let t=0;r>0&&t<n;t++)a[t]++,r--}c=a.reduce((t,e)=>t+e,0)}let u;if(l.reduce((t,e)=>t+e,0)+r<=e)u=l.map((t,e)=>Math.max(t,a[e]));else{const t=l.reduce((t,e,s)=>t+Math.max(0,e-a[s]),0),e=Math.max(0,o-c);u=a.map((s,i)=>{const n=l[i],r=Math.max(0,n-s);let o=0;return t>0&&(o=Math.floor(r/t*e)),s+o});let s=o-u.reduce((t,e)=>t+e,0);for(;s>0;){let t=!1;for(let e=0;e<n&&s>0;e++)u[e]<l[e]&&(u[e]++,s--,t=!0);if(!t)break}}const d=u.map(t=>"─".repeat(t));i.push(`┌─${d.join("─┬─")}─┐`);const p=t.header.map((t,e)=>{const i=this.renderInlineTokens(t.tokens||[],s);return this.wrapCellText(i,u[e])}),f=Math.max(...p.map(t=>t.length));for(let t=0;t<f;t++){const e=p.map((e,s)=>{const i=e[t]||"",n=i+" ".repeat(Math.max(0,u[s]-H(i)));return this.theme.bold(n)});i.push(`│ ${e.join(" │ ")} │`)}const g=`├─${u.map(t=>"─".repeat(t)).join("─┼─")}─┤`;i.push(g);for(let e=0;e<t.rows.length;e++){const n=t.rows[e].map((t,e)=>{const i=this.renderInlineTokens(t.tokens||[],s);return this.wrapCellText(i,u[e])}),r=Math.max(...n.map(t=>t.length));for(let t=0;t<r;t++){const e=n.map((e,s)=>{const i=e[t]||"";return i+" ".repeat(Math.max(0,u[s]-H(i)))});i.push(`│ ${e.join(" │ ")} │`)}e<t.rows.length-1&&i.push(g)}const m=u.map(t=>"─".repeat(t));return i.push(`└─${m.join("─┴─")}─┘`),i.push(""),i}}class Hs{items;filteredItems;theme;selectedIndex=0;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;constructor(t,e,s,i,n,r={}){this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=s,this.onChange=i,this.onCancel=n,this.searchEnabled=r.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Re)}updateValue(t,e){const s=this.items.find(e=>e.id===t);s&&(s.currentValue=e)}invalidate(){this.submenuComponent?.invalidate?.()}render(t){return this.submenuComponent?this.submenuComponent.render(t):this.renderMainList(t)}renderMainList(t){const e=[];if(this.searchEnabled&&this.searchInput&&(e.push(...this.searchInput.render(t)),e.push("")),0===this.items.length)return e.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(e,t),e;const s=this.searchEnabled?this.filteredItems:this.items;if(0===s.length)return e.push(tt(this.theme.hint(" No matching settings"),t)),this.addHintLine(e,t),e;const i=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),s.length-this.maxVisible)),n=Math.min(i+this.maxVisible,s.length),r=Math.min(30,Math.max(...this.items.map(t=>H(t.label))));for(let o=i;o<n;o++){const i=s[o];if(!i)continue;const n=o===this.selectedIndex,l=n?this.theme.cursor:" ",h=H(l),a=i.label+" ".repeat(Math.max(0,r-H(i.label))),c=this.theme.label(a,n),u=" ",d=t-(h+r+H(u))-2,p=this.theme.value(tt(i.currentValue,d,""),n);e.push(tt(l+c+u+p,t))}if(i>0||n<s.length){const i=` (${this.selectedIndex+1}/${s.length})`;e.push(this.theme.hint(tt(i,t-2,"")))}const o=s[this.selectedIndex];if(o?.description){e.push("");const s=N(o.description,t-4);for(const t of s)e.push(this.theme.description(` ${t}`))}return this.addHintLine(e,t),e}handleInput(t){if(this.submenuComponent)return void this.submenuComponent.handleInput?.(t);const e=zt(),s=this.searchEnabled?this.filteredItems:this.items;if(e.matches(t,"selectUp")){if(0===s.length)return;this.selectedIndex=0===this.selectedIndex?s.length-1:this.selectedIndex-1}else if(e.matches(t,"selectDown")){if(0===s.length)return;this.selectedIndex=this.selectedIndex===s.length-1?0:this.selectedIndex+1}else if(e.matches(t,"selectConfirm")||" "===t)this.activateItem();else if(e.matches(t,"selectCancel"))this.onCancel();else if(this.searchEnabled&&this.searchInput){const e=t.replace(/ /g,"");if(!e)return;this.searchInput.handleInput(e),this.applyFilter(this.searchInput.getValue())}}activateItem(){const t=this.searchEnabled?this.filteredItems[this.selectedIndex]:this.items[this.selectedIndex];if(t)if(t.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=t.submenu(t.currentValue,e=>{void 0!==e&&(t.currentValue=e,this.onChange(t.id,e)),this.closeSubmenu()});else if(t.values&&t.values.length>0){const e=(t.values.indexOf(t.currentValue)+1)%t.values.length,s=t.values[e];t.currentValue=s,this.onChange(t.id,s)}}closeSubmenu(){this.submenuComponent=null,null!==this.submenuItemIndex&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(t){this.filteredItems=h(this.items,t,t=>t.label),this.selectedIndex=0}addHintLine(t,e){t.push(""),t.push(tt(this.theme.hint(this.searchEnabled?" Type to search · Enter/Space to change · Esc to cancel":" Enter/Space to change · Esc to cancel"),e))}}class qs{lines;constructor(t=1){this.lines=t}setLines(t){this.lines=t}invalidate(){}render(t){const e=[];for(let t=0;t<this.lines;t++)e.push("");return e}}class js{text;paddingX;paddingY;constructor(t,e=0,s=0){this.text=t,this.paddingX=e,this.paddingY=s}invalidate(){}render(t){const e=[],s=" ".repeat(t);for(let t=0;t<this.paddingY;t++)e.push(s);const i=Math.max(1,t-2*this.paddingX);let n=this.text;const r=this.text.indexOf("\n");-1!==r&&(n=this.text.substring(0,r));const o=tt(n,i),l=" ".repeat(this.paddingX)+o+" ".repeat(this.paddingX),h=H(l),a=Math.max(0,t-h),c=l+" ".repeat(a);e.push(c);for(let t=0;t<this.paddingY;t++)e.push(s);return e}}var Ks=s(24434);const Ns="",Gs="[200~",Xs="[201~";function Qs(t){if(!t.startsWith(Ns))return"not-escape";if(1===t.length)return"incomplete";const e=t.slice(1);return e.startsWith("[")?e.startsWith("[M")?t.length>=6?"complete":"incomplete":function(t){if(!t.startsWith(`${Ns}[`))return"complete";if(t.length<3)return"incomplete";const e=t.slice(2),s=e[e.length-1],i=s.charCodeAt(0);if(i>=64&&i<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if("M"===s||"m"===s){const t=e.slice(1,-1).split(";");if(3===t.length&&t.every(t=>/^\d+$/.test(t)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}(t):e.startsWith("]")?function(t){if(!t.startsWith(`${Ns}]`))return"complete";if(t.endsWith(`${Ns}\\`)||t.endsWith(""))return"complete";return"incomplete"}(t):e.startsWith("P")?function(t){if(!t.startsWith(`${Ns}P`))return"complete";if(t.endsWith(`${Ns}\\`))return"complete";return"incomplete"}(t):e.startsWith("_")?function(t){if(!t.startsWith(`${Ns}_`))return"complete";if(t.endsWith(`${Ns}\\`))return"complete";return"incomplete"}(t):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length,"complete")}function Zs(t){const e=[];let s=0;for(;s<t.length;){const i=t.slice(s);if(i.startsWith(Ns)){let t=1;for(;t<=i.length;){const n=i.slice(0,t),r=Qs(n);if("complete"===r){e.push(n),s+=t;break}if("incomplete"!==r){e.push(n),s+=t;break}t++}if(t>i.length)return{sequences:e,remainder:i}}else e.push(i[0]),s++}return{sequences:e,remainder:""}}class Ys extends Ks.EventEmitter{buffer="";timeout=null;timeoutMs;pasteMode=!1;pasteBuffer="";constructor(t={}){super(),this.timeoutMs=t.timeout??10}process(t){let e;if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),Buffer.isBuffer(t))if(1===t.length&&t[0]>127){const s=t[0]-128;e=`${String.fromCharCode(s)}`}else e=t.toString();else e=t;if(0===e.length&&0===this.buffer.length)return void this.emit("data","");if(this.buffer+=e,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";const t=this.pasteBuffer.indexOf(Xs);if(-1!==t){const e=this.pasteBuffer.slice(0,t),s=this.pasteBuffer.slice(t+6);this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",e),s.length>0&&this.process(s)}return}const s=this.buffer.indexOf(Gs);if(-1!==s){if(s>0){const t=Zs(this.buffer.slice(0,s));for(const e of t.sequences)this.emit("data",e)}this.buffer=this.buffer.slice(s+6),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";const t=this.pasteBuffer.indexOf(Xs);if(-1!==t){const e=this.pasteBuffer.slice(0,t),s=this.pasteBuffer.slice(t+6);this.pasteMode=!1,this.pasteBuffer="",this.emit("paste",e),s.length>0&&this.process(s)}return}const i=Zs(this.buffer);this.buffer=i.remainder;for(const t of i.sequences)this.emit("data",t);this.buffer.length>0&&(this.timeout=setTimeout(()=>{const t=this.flush();for(const e of t)this.emit("data",e)},this.timeoutMs))}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),0===this.buffer.length)return[];const t=[this.buffer];return this.buffer="",t}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer=""}getBuffer(){return this.buffer}destroy(){this.clear()}}const Js=(0,s(98995).createRequire)(require("url").pathToFileURL(__filename).href);class ti{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;stdinBuffer;stdinDataHandler;writeLogPath=process.env.PI_TUI_WRITE_LOG||"";get kittyProtocolActive(){return this._kittyProtocolActive}start(t,e){this.inputHandler=t,this.resizeHandler=e,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("[?2004h"),process.stdout.on("resize",this.resizeHandler),"win32"!==process.platform&&process.kill(process.pid,"SIGWINCH"),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new Ys({timeout:10});const t=/^\x1b\[\?(\d+)u$/;this.stdinBuffer.on("data",e=>{if(!this._kittyProtocolActive){if(e.match(t))return this._kittyProtocolActive=!0,ot(!0),void process.stdout.write("[>7u")}this.inputHandler&&this.inputHandler(e)}),this.stdinBuffer.on("paste",t=>{this.inputHandler&&this.inputHandler(`[200~${t}[201~`)}),this.stdinDataHandler=t=>{this.stdinBuffer.process(t)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),process.stdout.write("[?u"),setTimeout(()=>{this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("[>4;2m"),this._modifyOtherKeysActive=!0)},150)}enableWindowsVTInput(){if("win32"===process.platform)try{const t=Js("koffi").load("kernel32.dll"),e=t.func("void* __stdcall GetStdHandle(int)"),s=t.func("bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)"),i=t.func("bool __stdcall SetConsoleMode(void*, uint32_t)"),n=512,r=e(-10),o=new Uint32Array(1);s(r,o),i(r,o[0]|n)}catch{}}async drainInput(t=1e3,e=50){this._kittyProtocolActive&&(process.stdout.write("[<u"),this._kittyProtocolActive=!1,ot(!1)),this._modifyOtherKeysActive&&(process.stdout.write("[>4;0m"),this._modifyOtherKeysActive=!1);const s=this.inputHandler;this.inputHandler=void 0;let i=Date.now();const n=()=>{i=Date.now()};process.stdin.on("data",n);const r=Date.now()+t;try{for(;;){const t=Date.now(),s=r-t;if(s<=0)break;if(t-i>=e)break;await new Promise(t=>setTimeout(t,Math.min(e,s)))}}finally{process.stdin.removeListener("data",n),this.inputHandler=s}}stop(){process.stdout.write("[?2004l"),this._kittyProtocolActive&&(process.stdout.write("[<u"),this._kittyProtocolActive=!1,ot(!1)),this._modifyOtherKeysActive&&(process.stdout.write("[>4;0m"),this._modifyOtherKeysActive=!1),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(t){if(process.stdout.write(t),this.writeLogPath)try{Kt.appendFileSync(this.writeLogPath,t,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||80}get rows(){return process.stdout.rows||24}moveBy(t){t>0?process.stdout.write(`[${t}B`):t<0&&process.stdout.write(`[${-t}A`)}hideCursor(){process.stdout.write("[?25l")}showCursor(){process.stdout.write("[?25h")}clearLine(){process.stdout.write("")}clearFromCursor(){process.stdout.write("")}clearScreen(){process.stdout.write("")}setTitle(t){process.stdout.write(`]0;${t}`)}}}};