dsh-aiterm 0.5.0 → 0.5.12
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.
- package/CONTRACTS.md +104 -22
- package/README.md +208 -26
- package/client/HistoryPanel.jsx +342 -29
- package/client/api.js +44 -3
- package/client/locale.js +40 -2
- package/cordis.patch.yml +1 -0
- package/lib/client.js +30 -30
- package/lib/host/autolog.js +107 -4
- package/lib/host/config.js +14 -0
- package/lib/host/disclosure.js +357 -0
- package/lib/host/exporter.js +447 -159
- package/lib/host/history-store.js +1735 -295
- package/lib/host/permission.js +13 -0
- package/lib/host/prompt.js +24 -4
- package/lib/host/registry.js +858 -76
- package/lib/host/routes.js +45 -2
- package/lib/host/tools.js +280 -22
- package/lib/host/transports/ssh.js +1 -1
- package/lib/index.js +2 -2
- package/package.json +8 -6
- package/scripts/build-vendor.mjs +37 -0
- package/scripts/smoke-client.mjs +193 -6
- package/vendor/README.md +31 -0
- package/vendor/ssh2.LICENSE +19 -0
- package/vendor/ssh2.cjs +20124 -0
package/lib/client.js
CHANGED
|
@@ -8,7 +8,7 @@ window.__ModuleLoader__.load({
|
|
|
8
8
|
factory(require) {
|
|
9
9
|
var module = { exports: {} };
|
|
10
10
|
var exports = module.exports;
|
|
11
|
-
var Ar=Object.defineProperty;var Ic=Object.getOwnPropertyDescriptor;var Oc=Object.getOwnPropertyNames;var Nc=Object.prototype.hasOwnProperty;var Fc=(e,t)=>{for(var i in t)Ar(e,i,{get:t[i],enumerable:!0})},Hc=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Oc(t))!Nc.call(e,r)&&r!==i&&Ar(e,r,{get:()=>t[r],enumerable:!(s=Ic(t,r))||s.enumerable});return e};var Wc=e=>Hc(Ar({},"__esModule",{value:!0}),e);var E_={};Fc(E_,{TAB_ID:()=>Er,TAB_KIND:()=>Rr,apply:()=>k_,inject:()=>x_});module.exports=Wc(E_);var Wi="aiterm",No={title:"aiterm",guide:"连接 SSH 或 Telnet 服务器,与 AI 协同操作同一个终端",sessions:"会话",newSession:"新建会话",noSessions:"暂无终端会话",noSessionsHint:"新建一个 SSH 或 Telnet 连接开始使用;AI 也可以在这里创建会话。",loading:"加载中…",stateConnecting:"连接中",stateOpen:"已连接",stateDisconnected:"已断开",stateClosed:"已关闭",stateFailed:"连接失败",stateUnknown:"未知",connectTitle:"新建连接",transport:"协议",profile:"配置",profileManual:"手动填写",profileLoading:"正在读取配置…",profileEmpty:"暂无保存的配置",profileLoadFailed:"读取配置失败:{message}",host:"主机",port:"端口",username:"用户名",authType:"认证方式",authPassword:"密码",authPrivateKey:"私钥",authAgent:"SSH Agent",authNone:"无",password:"密码",passwordHint:"密码只用于建立连接,不会回显,也不会写进会话记录。",profileUsesSavedSecret:"将使用该配置中保存的凭据;留空即可。",profileNeedsSecretHint:"该配置没有保存密码,请在上方填写;勾选「保存为配置」可下次免填。",errMissingSecret:"这条配置里没有保存密码或私钥,请在上方填写后再连接。",errAiSecretDenied:"AI 不能代替你提供密码或私钥;请改用已保存凭据的配置,或由你手动连接。",errProfileNotFound:"这条配置已不存在(可能已被删除),刷新后重试。",privateKey:"私钥(PEM)",privateKeyHint:"粘贴 PEM 私钥内容;可留空表示使用配置中保存的私钥。",passphrase:"私钥口令",saveProfile:"保存为配置",profileName:"配置名称",connectAction:"连接",connectingAction:"正在连接…",cancel:"取消",permission:"AI 权限",permRo:"只读",permWo:"只写",permRw:"读写",permRoHint:"AI 只读:可以查看终端输出,但不能输入",permWoHint:"AI 只写:可以向终端输入,但不能读取输出",permRwHint:"AI 读写:可以输入并读取终端输出",lockAi:"AI 控制中",lockHuman:"人工接管中",lockFree:"空闲",lockAiCountdown:"{seconds}s 后自动释放",takeOver:"接管",releaseAi:"交还 AI",takeOverFailed:"接管失败:{message}",releaseFailed:"交还失败:{message}",accessFailed:"切换 AI 权限失败:{message}",blockedTitle:"AI 正在操作,人工输入已锁定",blockedHint:"接管后即可自行输入;AI 的输入会被拒绝。",takeOverInline:"立即接管",audit:"审计",auditEmpty:"暂无审计记录",auditLoading:"正在读取审计记录…",auditRead:"读取",auditWrite:"写入",auditDeny:"拒绝",auditLock:"锁定",auditFailed:"读取审计记录失败:{message}",sourceAi:"AI",sourceHuman:"人工",close:"关闭",closeSession:"关闭会话",closeConfirm:"确认关闭",closeFailed:"关闭会话失败:{message}",closeHint:"关闭后远程连接会断开。",closedTitle:"连接已关闭",failedTitle:"连接失败",closedReason:"原因:{reason}",reconnect:"重新连接",reconnecting:"连接中断,正在重连…",linkOpen:"已连接",linkConnecting:"连接中",disconnect:"中断",disconnectHint:"中断连接但保留会话,可稍后重连",disconnectFailed:"中断连接失败:{message}",disconnectedNotice:"已断开连接;会话已保留,可随时重连",disconnectedTitle:"连接已断开",disconnectedHint:"会话仍保留;重连后屏幕会重置。断开期间输入与复制屏幕不可用。",reconnectAction:"重连",reconnectingAction:"重连中…",reconnectFailed:"重连失败:{message}",reconnected:"已重新连接",terminalResetNotice:"── 已重新连接 · 屏幕已重置 ──",copyScreenUnavailable:"会话已断开,无法复制屏幕文本",back:"返回",connectHint:"选择已保存的配置,或手动填写连接信息",closeSessionPrompt:"关闭会话「{title}」?",profilesDeletePrompt:"确认删除配置「{name}」?",profilesActionFailed:"配置操作失败:{message}",scriptsDeletePrompt:"删除脚本「{name}」?",statusSize:"{cols}×{rows}",statusBytes:"收 {in} / 发 {out}",sessionEnded:"远程会话已结束",sessionExited:"会话已退出({code})",inputFailed:"发送输入失败:{message}",inputOverflow:"输入过快,已丢弃部分内容",unknownError:"未知错误",errorHostRequired:"请填写主机地址",errorUsernameRequired:"SSH 连接需要用户名",errorPort:"端口必须是 1-65535 之间的数字",connectFailed:"连接失败:{message}",profileSaveFailed:"会话已建立,但保存配置失败:{message}",profileNameRequired:"请填写配置名称",takenOver:"已接管终端",released:"已交还 AI",accessChanged:"AI 权限已更新",copied:"已复制",history:"历史",historyTitle:"终端历史",historyPanelClose:"关闭历史",historySessionsTitle:"历史会话",historyLoadingSessions:"正在读取历史会话…",historySessionsEmpty:"暂无历史会话",historySessionsFailed:"读取历史会话失败:{message}",historyOngoing:"进行中",historySince:"起始时间",historyUntil:"结束时间",historyTimeHint:"如 10m / 2h / 90s / ISO 时间,留空不限",historySearch:"关键字",historySearchHint:"正则或纯文本;正则无效时按文本匹配",historyContext:"上下文",historyQuery:"查询",historyQuerying:"查询中…",historyTimeInvalid:"时间格式无效:{value}",historyQueryFailed:"查询历史失败:{message}",historyNoMatches:"没有匹配的历史输出",historyNoMatchesHint:"调整时间范围或关键字后重试。",historyFragment:"未设置关键字,下面是该时间段的原始输出片段",historyNeedSession:"请先选择一个历史会话",historyFooter:"扫描 {size} · 结果 {count} 条",historyTruncated:"已达扫描上限,结果可能不完整",historyCopy:"复制结果",historyCopyFailed:"无法访问剪贴板,请手动复制",historyLogFileTitle:"日志文件",historyExportOne:"导出当前",historyExportAll:"导出全部",historyExportHint:"把当前会话的输出导出成文本文件(默认目录 {dir})",historyExportAllHint:"把所有会话(含已关闭)的输出各导出一个文本文件",historyExportDone:"已导出 {count} 个文件",historyExportEmpty:"没有可导出的内容",historyExportWhere:"已写入 {dir}",historyExportLines:"{count} 行",historyExportFailed:"导出失败:{message}",historyExportNeedsRestart:"当前 DSH 进程还不支持日志导出:重启 DSH 后可用(客户端已更新,宿主代码需重启加载)。",historyAutoLogLabel:"自动把每个会话写进日志文件",historyAutoLogOffHint:"默认关闭。开启后每个会话实时追加写入磁盘文件。",historyAutoLogWhere:"正在写入 {dir}",historyAutoLogOn:"已开启自动写日志",historyAutoLogOff:"已关闭自动写日志",historyAutoLogFailed:"切换失败:{message}",historyManualCopy:"手动复制",historyEmptyQuery:"选择会话后会自动查询;也可调整条件后点击“查询”。",scripts:"脚本",scriptsTitle:"脚本",scriptsPanelClose:"关闭脚本",scriptsLoading:"正在读取脚本…",scriptsEmpty:"暂无脚本",scriptsEmptyHint:"在下方粘贴 JSON 定义并保存,或让 AI 创建脚本。",scriptsListFailed:"读取脚本失败:{message}",scriptsParams:"参数",scriptsNoParams:"无需参数",scriptsTarget:"运行目标",scriptsTargetCurrent:"当前会话",scriptsTargetPicked:"选定会话",scriptsTargetPickedHint:"已勾选 {count} 个会话",scriptsTargetPickedEmpty:"请至少勾选一个会话",scriptsTargetAll:"全部会话",scriptsTargetAllHint:"对 {count} 个已打开的会话执行",scriptsTargetNoSessions:"当前没有已打开的会话",scriptsNewAction:"新建",scriptsNewMacro:"新建 · 逐行命令",scriptsNewJson:"新建 · 高级脚本",scriptsRun:"运行",scriptsRunning:"运行中…",scriptsRunFailed:"运行脚本失败:{message}",scriptsRunDone:"执行完成",scriptsRunTimedOut:"执行超时,已中止",scriptsRunSummary:"共 {runs} 个会话,{ok} 个成功",scriptsProgressEmpty:"运行后将在此显示每一步的结果",scriptsSave:"保存脚本",scriptsSaveHint:'粘贴脚本 JSON:{"name","description","params","steps"}',scriptsSaveReplaceHint:"保存会整体替换同名脚本,请补全 steps。",scriptsSaveAction:"保存",scriptsCancel:"取消",scriptsSaved:"脚本已保存",scriptsJsonInvalid:"JSON 解析失败:{message}",scriptsJsonObject:"脚本必须是 JSON 对象",scriptsDelete:"删除",scriptsDeleteConfirm:"确认删除",scriptsDeleted:"脚本已删除",scriptsDeleteFailed:"删除失败:{message}",scriptsEdit:"编辑",scriptsSteps:"{count} 步(含嵌套)",scriptsParamsCount:"{count} 个参数",scriptsGroupCount:"{count} 个脚本",scriptsGetFailed:"读取脚本失败:{message}",scriptsGetInvalid:"读取脚本失败:Host 未返回脚本定义",scriptsLoadingEditor:"正在读取脚本…",scriptsEmptySaveWarn:"该脚本原有 {count} 个步骤,当前 steps 为空;再次点击“仍要保存空脚本”才会保存。",scriptsEmptySaveConfirm:"仍要保存空脚本",copyScreen:"复制当前屏幕文本",copyScreenDone:"屏幕文本已复制",copyScreenEmpty:"当前屏幕没有文本",copyScreenFailed:"复制屏幕文本失败:{message}",copyFailed:"无法访问剪贴板,请手动复制",profiles:"配置管理",profilesTitle:"配置管理",profilesPanelClose:"关闭配置管理",profilesLoading:"正在读取配置…",profilesEmpty:"暂无保存的配置",profilesEmptyHint:"新建连接时勾选“保存为配置”,或让 AI 帮你保存一个。",profilesListFailed:"读取配置失败:{message}",profilesFooter:"{profiles} 个配置 · {folders} 个分组",profilesReload:"刷新",profilesUngrouped:"未分组",profilesFolderCount:"{count} 个配置",profilesBadgePassword:"密码",profilesBadgePrivateKey:"私钥",profilesBadgePassphrase:"口令",profilesConnect:"连接",profilesEdit:"编辑",profilesRename:"重命名",profilesMove:"移动到分组",profilesDelete:"删除",profilesDeleteConfirm:"确认删除",profilesDeleteDone:"配置已删除",profilesDeleteFailed:"删除配置失败:{message}",profilesRenamed:"配置已重命名",profilesRenameFailed:"重命名失败:{message}",profilesMoved:"已移动分组",profilesMoveFailed:"移动分组失败:{message}",profilesNameRequired:"配置名称不能为空",profilesNamePlaceholder:"配置名称",profilesRenameSave:"保存",profilesRenameCancel:"取消",profilesNewConnection:"新建连接",profilesNewFolder:"新建分组",profilesNewFolderPlaceholder:"分组名称",profilesCreateFolder:"创建",profilesFolderAdded:"已创建分组“{name}”",profilesFolderNameRequired:"分组名称不能为空",profilesConnectFailed:"连接失败:{message}",profilesEditHint:"密钥类字段留空表示保留已保存的凭据;保存后可在配置管理中连接。",profilesEditTitle:"编辑配置",profilesSaveAction:"保存修改",profilesSaved:"配置已保存",profilesSaveFailed:"保存配置失败:{message}",folder:"分组",folderNone:"未分组",folderNew:"新建分组…",folderName:"分组名称",scriptsTemplate:"模板",scriptsNewType:"新建类型",scriptsTemplateCmd:"发送命令",scriptsTemplateWait:"等待(@wait)",scriptsTemplateSet:"设置变量(@set)",scriptsTemplateLog:"输出日志(@log)",scriptsTemplateExpect:"断言(@expect)",scriptsTemplatePlaceholder:"插入模板…",scriptsTemplateRebuilt:"当前 JSON 无法解析,已用模板重建脚本",scriptsUngrouped:"未分组",scriptsMode:"编写方式",scriptsModeMacro:"逐行命令",scriptsModeJson:"JSON(高级)",scriptsJsonHint:"完整的步骤数组,支持 if/loop 等高级结构。",scriptsMacroHint:"每行一条命令,直接发送;以 @ 开头是控制行。",scriptsMacroHelp:"示例:ls -l / @wait 500 / @wait 2s / @set name = value / @log 说明 / @expect 匹配文本 / @python … @end(发到远端 shell 里执行)",scriptsMacroWait:"每条命令发送后等它跑完(等输出停顿)",scriptsMacroWaitHint:"不勾选时命令会连续发出,可能还没回显就发送下一条。",scriptsMacroParseError:"第 {line} 行:{message}",scriptsMacroNoSteps:"至少写一条命令",scriptsMacroUnsupported:"这个脚本含 if/loop 等结构化步骤,只能在 JSON 模式编辑。",scriptsTemplatePython:"Python(远端执行)",quickScripts:"快捷脚本",scriptsName:"名称",scriptsNameHint:"同名脚本会被覆盖。",scriptsNameRequired:"请填写脚本名称",scriptsFolder:"分组",scriptsFolderCreate:"+ 新建分组…",scriptsFolderNew:"分组名",scriptsFolderUse:"使用",scriptsFolderRename:"重命名分组",scriptsFolderDelete:"删除分组",scriptsFolderDeletePrompt:"删除分组「{name}」?组内脚本会移到未分组。",scriptsFolderRenamed:"分组已重命名",scriptsFolderDeleted:"分组已删除,脚本已移到未分组",scriptsFolderFailed:"分组操作失败:{message}",scriptsMoveToFolder:"移到分组",quickFolderVisibility:"分组显示",quickFolderAll:"显示全部分组",quickViewResult:"查看结果",scriptsViewResult:"查看结果",scriptsFolderAdd:"添加分组",scriptsFolderScope:"当前分组",scriptsFolderAdded:"已添加分组「{name}」",scriptsMoveUp:"上移",scriptsMoveDown:"下移",scriptsCopy:"复制",scriptsCopied:"已复制为 {name}",scriptsCopyFailed:"复制脚本失败:{message}",scriptsResultTitle:"运行结果",scriptsResultClose:"关闭结果",scriptsResultRunning:"运行中 · {steps} 步",scriptsResultDone:"运行完成 · {steps} 步",scriptsEditorEmpty:"从左侧选择一个脚本,或点「+ 新建」开始编写。",scriptsFolderEmpty:"这个分组下还没有脚本,点左侧「+ 新建」添加。",scriptsRunCollapsed:"运行完成 · {steps} 步",scriptsRunExpand:"展开结果",scriptsRunCollapse:"收起结果",quickScriptsShow:"⚡ 快捷脚本",quickScriptsHide:"收起",quickScriptsManage:"管理",quickScriptsEmpty:"暂无脚本;在「脚本」面板里新建,保存后会出现在这里。",quickScriptsLoadFailed:"读取脚本失败",quickScriptsNoSession:"先连接一个会话再运行快捷脚本",quickScriptsDone:"已运行 {name}",quickScriptsPartial:"{name} 已运行,但有 {failed} 个目标失败",quickScriptsFailed:"{name} 运行失败:{message}",scriptsValidateAt:"{path} · {message}",scriptsValidateMore:"另有 {count} 处问题",tplSend:"发送命令",tplDelay:"延迟",tplSet:"设置变量",tplIf:"条件分支 (if)",tplLoop:"循环 (loop)",tplExpect:"断言 (expect)",tplLog:"输出日志",kindSend:"发送命令",kindDelay:"延迟",kindSet:"设置变量",kindLog:"输出日志",kindExpect:"断言",kindIf:"条件分支",kindLoop:"循环",kindUnknown:"未知",vStepObject:"步骤必须是 JSON 对象",vNoKind:"步骤缺少类型(send/delay/set/log/expect/if/loop 之一)",vMultiKind:"一个步骤不能同时包含多种类型:{kinds}",vUnknownKind:"未知步骤类型:{kind}",vSend:"send 必须是非空字符串",vDelay:"delay 必须是大于 0 的毫秒数",vSetName:"set 变量名必须匹配 [A-Za-z_][A-Za-z0-9_]{0,31}",vSetValue:"set.value 必须是字符串",vLog:"log 必须是字符串",vExpect:"expect 缺少条件对象",vExpectOnFail:"expect.onFail 只能是 stop 或 continue",vIfThen:"if 缺少 then 步骤数组",vIfThenEmpty:"if 的 then 不能为空",vIfElse:"if 的 else 必须是步骤数组",vLoopBody:"loop 缺少 steps 步骤数组",vLoopCond:"loop 需要 count / while / until 至少一个",vLoopCount:"loop.count 必须是 1-1000 之间的正整数",vLoopMax:"loop.maxIterations 必须是 1-1000 之间的正整数",vCondition:"条件必须是 always/match/contains/variable/not/all/any 之一",vConditionList:"{key} 必须是非空的条件数组",vConditionRegex:"正则表达式无效",vConditionDeep:"条件嵌套超过上限({max} 层)",vSteps:"steps 必须是步骤数组",vTooDeep:"嵌套深度超过上限({max} 层)",vTooMany:"步骤总数超过上限({max})"},Fo={title:"aiterm",guide:"Open an SSH or Telnet session and share the terminal with the AI",sessions:"Sessions",newSession:"New session",noSessions:"No terminal sessions yet",noSessionsHint:"Create an SSH or Telnet connection to get started. The AI can open sessions here too.",loading:"Loading…",stateConnecting:"Connecting",stateOpen:"Connected",stateDisconnected:"Disconnected",stateClosed:"Closed",stateFailed:"Failed",stateUnknown:"Unknown",connectTitle:"New connection",transport:"Protocol",profile:"Profile",profileManual:"Enter manually",profileLoading:"Loading profiles…",profileEmpty:"No saved profiles",profileLoadFailed:"Could not load profiles: {message}",host:"Host",port:"Port",username:"Username",authType:"Authentication",authPassword:"Password",authPrivateKey:"Private key",authAgent:"SSH agent",authNone:"None",password:"Password",passwordHint:"The password is used only to connect. It is never echoed or stored in the session log.",profileUsesSavedSecret:"The credentials saved in this profile are used; leave the field empty.",profileNeedsSecretHint:'This profile has no saved password — type it above. Tick "Save as profile" to skip it next time.',errMissingSecret:"This profile has no saved password or key — fill it in above, then connect.",errAiSecretDenied:"The AI may not supply a password or key for you. Use a profile with saved credentials, or connect manually.",errProfileNotFound:"This profile no longer exists (it may have been deleted). Refresh and try again.",privateKey:"Private key (PEM)",privateKeyHint:"Paste a PEM private key, or leave empty to use the key saved in the profile.",passphrase:"Key passphrase",saveProfile:"Save as profile",profileName:"Profile name",connectAction:"Connect",connectingAction:"Connecting…",cancel:"Cancel",permission:"AI access",permRo:"Read",permWo:"Write",permRw:"Read+write",permRoHint:"AI can read terminal output but cannot send input",permWoHint:"AI can send input but cannot read terminal output",permRwHint:"AI can send input and read terminal output",lockAi:"AI in control",lockHuman:"Human in control",lockFree:"Idle",lockAiCountdown:"auto-release in {seconds}s",takeOver:"Take over",releaseAi:"Hand back to AI",takeOverFailed:"Could not take over: {message}",releaseFailed:"Could not hand back: {message}",accessFailed:"Could not change AI access: {message}",blockedTitle:"The AI is using this terminal — human input is locked",blockedHint:"Take over to type. AI input is refused while you hold control.",takeOverInline:"Take over now",audit:"Audit",auditEmpty:"No audit entries",auditLoading:"Loading audit entries…",auditRead:"read",auditWrite:"write",auditDeny:"deny",auditLock:"lock",auditFailed:"Could not load audit entries: {message}",sourceAi:"AI",sourceHuman:"Human",close:"Close",closeSession:"Close session",closeConfirm:"Confirm close",closeFailed:"Could not close the session: {message}",closeHint:"Closing disconnects the remote connection.",closedTitle:"Connection closed",failedTitle:"Connection failed",closedReason:"Reason: {reason}",reconnect:"Reconnect",reconnecting:"Connection lost, reconnecting…",linkOpen:"Connected",linkConnecting:"Connecting",disconnect:"Disconnect",disconnectHint:"Disconnect but keep the session; reconnect later",disconnectFailed:"Could not disconnect: {message}",disconnectedNotice:"Disconnected — the session is kept and can be reconnected",disconnectedTitle:"Connection lost",disconnectedHint:"The session is kept. Reconnecting resets the screen. Input and screen copy stay disabled while disconnected.",reconnectAction:"Reconnect",reconnectingAction:"Reconnecting…",reconnectFailed:"Could not reconnect: {message}",reconnected:"Reconnected",terminalResetNotice:"── Reconnected · screen reset ──",copyScreenUnavailable:"The session is disconnected; screen text cannot be copied",back:"Back",connectHint:"Pick a saved profile, or enter the connection details",closeSessionPrompt:"Close session “{title}”?",profilesDeletePrompt:"Delete profile “{name}”?",profilesActionFailed:"Profile action failed: {message}",scriptsDeletePrompt:"Delete script “{name}”?",statusSize:"{cols}×{rows}",statusBytes:"in {in} / out {out}",sessionEnded:"The remote session ended",sessionExited:"Session exited ({code})",inputFailed:"Could not send input: {message}",inputOverflow:"Input was too fast; some keystrokes were dropped",unknownError:"Unknown error",errorHostRequired:"Enter a host",errorUsernameRequired:"SSH needs a username",errorPort:"The port must be a number between 1 and 65535",connectFailed:"Connection failed: {message}",profileSaveFailed:"Session opened, but saving the profile failed: {message}",profileNameRequired:"Enter a profile name",takenOver:"You now control the terminal",released:"Control handed back to the AI",accessChanged:"AI access updated",copied:"Copied",history:"History",historyTitle:"Terminal history",historyPanelClose:"Close history",historySessionsTitle:"History sessions",historyLoadingSessions:"Loading history sessions…",historySessionsEmpty:"No history sessions yet",historySessionsFailed:"Could not load history sessions: {message}",historyOngoing:"active",historySince:"Since",historyUntil:"Until",historyTimeHint:"e.g. 10m / 2h / 90s / ISO time; empty means unbounded",historySearch:"Keyword",historySearchHint:"Regex or plain text; an invalid regex is matched literally",historyContext:"Context",historyQuery:"Search",historyQuerying:"Searching…",historyTimeInvalid:"Invalid time value: {value}",historyQueryFailed:"Could not query history: {message}",historyNoMatches:"No matching history output",historyNoMatchesHint:"Adjust the time range or keyword and try again.",historyFragment:"No keyword set — showing the raw output slice for this time range",historyNeedSession:"Select a history session first",historyFooter:"Scanned {size} · {count} matches",historyTruncated:"Scan cap reached; results may be incomplete",historyCopy:"Copy results",historyCopyFailed:"Clipboard unavailable — copy manually",historyLogFileTitle:"Log files",historyExportOne:"Export this",historyExportAll:"Export all",historyExportHint:"Write this session's output to a text file (default {dir})",historyExportAllHint:"Write one text file per session, including closed ones",historyExportDone:"Exported {count} file(s)",historyExportEmpty:"Nothing to export",historyExportWhere:"Written to {dir}",historyExportLines:"{count} lines",historyExportFailed:"Export failed: {message}",historyExportNeedsRestart:"This DSH process cannot export logs yet: restart DSH to load the Host half.",historyAutoLogLabel:"Write every session to a log file",historyAutoLogOffHint:"Off by default. When on, each session appends to a file on disk in real time.",historyAutoLogWhere:"Writing to {dir}",historyAutoLogOn:"Auto-log enabled",historyAutoLogOff:"Auto-log disabled",historyAutoLogFailed:"Could not switch: {message}",historyManualCopy:"Manual copy",historyEmptyQuery:"The selected session is queried automatically; adjust the filters and search again.",scripts:"Scripts",scriptsTitle:"Scripts",scriptsPanelClose:"Close scripts",scriptsLoading:"Loading scripts…",scriptsEmpty:"No scripts yet",scriptsEmptyHint:"Paste a JSON definition below and save it, or let the AI create one.",scriptsListFailed:"Could not load scripts: {message}",scriptsParams:"Parameters",scriptsNoParams:"No parameters",scriptsTarget:"Target",scriptsTargetCurrent:"This session",scriptsTargetPicked:"Pick sessions",scriptsTargetPickedHint:"{count} session(s) ticked",scriptsTargetPickedEmpty:"Tick at least one session",scriptsTargetAll:"All sessions",scriptsTargetAllHint:"Runs on {count} open sessions",scriptsTargetNoSessions:"There are no open sessions",scriptsNewAction:"New",scriptsNewMacro:"New · commands",scriptsNewJson:"New · advanced",scriptsRun:"Run",scriptsRunning:"Running…",scriptsRunFailed:"Could not run the script: {message}",scriptsRunDone:"Finished",scriptsRunTimedOut:"Timed out and aborted",scriptsRunSummary:"{runs} sessions, {ok} succeeded",scriptsProgressEmpty:"Step results appear here after a run",scriptsSave:"Save script",scriptsSaveHint:'Paste script JSON: {"name","description","params","steps"}',scriptsSaveReplaceHint:"Saving replaces the script with this JSON; include its steps.",scriptsSaveAction:"Save",scriptsCancel:"Cancel",scriptsSaved:"Script saved",scriptsJsonInvalid:"Invalid JSON: {message}",scriptsJsonObject:"The script must be a JSON object",scriptsDelete:"Delete",scriptsDeleteConfirm:"Confirm delete",scriptsDeleted:"Script deleted",scriptsDeleteFailed:"Could not delete: {message}",scriptsEdit:"Edit",scriptsSteps:"{count} steps (incl. nested)",scriptsParamsCount:"{count} params",scriptsGroupCount:"{count} scripts",scriptsGetFailed:"Could not load the script: {message}",scriptsGetInvalid:"Could not load the script: the Host returned no script definition",scriptsLoadingEditor:"Loading script…",scriptsEmptySaveWarn:"This script had {count} steps and steps is now empty; click “Save empty program” again to confirm.",scriptsEmptySaveConfirm:"Save empty program",copyScreen:"Copy screen text",copyScreenDone:"Screen text copied",copyScreenEmpty:"The screen is empty",copyScreenFailed:"Could not copy the screen text: {message}",copyFailed:"Clipboard unavailable — copy manually",profiles:"Profiles",profilesTitle:"Manage profiles",profilesPanelClose:"Close profiles",profilesLoading:"Loading profiles…",profilesEmpty:"No saved profiles",profilesEmptyHint:"Tick “Save as profile” when connecting, or let the AI save one for you.",profilesListFailed:"Could not load profiles: {message}",profilesFooter:"{profiles} profiles · {folders} folders",profilesReload:"Refresh",profilesUngrouped:"Ungrouped",profilesFolderCount:"{count} profiles",profilesBadgePassword:"password",profilesBadgePrivateKey:"key",profilesBadgePassphrase:"passphrase",profilesConnect:"Connect",profilesEdit:"Edit",profilesRename:"Rename",profilesMove:"Move to folder",profilesDelete:"Delete",profilesDeleteConfirm:"Confirm delete",profilesDeleteDone:"Profile deleted",profilesDeleteFailed:"Could not delete the profile: {message}",profilesRenamed:"Profile renamed",profilesRenameFailed:"Could not rename the profile: {message}",profilesMoved:"Profile moved",profilesMoveFailed:"Could not move the profile: {message}",profilesNameRequired:"A profile name is required",profilesNamePlaceholder:"Profile name",profilesRenameSave:"Save",profilesRenameCancel:"Cancel",profilesNewConnection:"New connection",profilesNewFolder:"New folder",profilesNewFolderPlaceholder:"Folder name",profilesCreateFolder:"Create",profilesFolderAdded:"Folder “{name}” created",profilesFolderNameRequired:"A folder name is required",profilesConnectFailed:"Could not connect: {message}",profilesEditHint:"Leave secret fields blank to keep the saved credentials; save, then connect from profiles.",profilesEditTitle:"Edit profile",profilesSaveAction:"Save changes",profilesSaved:"Profile saved",profilesSaveFailed:"Could not save the profile: {message}",folder:"Folder",folderNone:"Ungrouped",folderNew:"New folder…",folderName:"Folder name",scriptsTemplate:"Template",scriptsNewType:"Create as",scriptsTemplateCmd:"Send command",scriptsTemplateWait:"Wait (@wait)",scriptsTemplateSet:"Set variable (@set)",scriptsTemplateLog:"Log line (@log)",scriptsTemplateExpect:"Assert (@expect)",scriptsTemplatePlaceholder:"Insert template…",scriptsTemplateRebuilt:"The current JSON could not be parsed, so the script was rebuilt from the template",scriptsUngrouped:"Ungrouped",scriptsMode:"Editing mode",scriptsModeMacro:"One command per line",scriptsModeJson:"JSON (advanced)",scriptsJsonHint:"The full step array, including if/loop structures.",scriptsMacroHint:"Each line is sent as a command; lines starting with @ are directives.",scriptsMacroHelp:"Examples: ls -l / @wait 500 / @wait 2s / @set name = value / @log note / @expect pattern / @python … @end (runs on the remote shell)",scriptsMacroWait:"Wait for each command to finish (output goes idle)",scriptsMacroWaitHint:"Unchecked, lines are sent back to back and may race the prompt.",scriptsMacroParseError:"line {line}: {message}",scriptsMacroNoSteps:"Write at least one command",scriptsMacroUnsupported:"This script uses if/loop steps, so it can only be edited as JSON.",scriptsTemplatePython:"Python (remote)",quickScripts:"Quick scripts",scriptsName:"Name",scriptsNameHint:"An existing script with the same name is overwritten.",scriptsNameRequired:"Enter a script name",scriptsFolder:"Folder",scriptsFolderCreate:"+ New folder…",scriptsFolderNew:"Folder name",scriptsFolderUse:"Use",scriptsFolderRename:"Rename folder",scriptsFolderDelete:"Delete folder",scriptsFolderDeletePrompt:'Delete folder "{name}"? Its scripts move to Ungrouped.',scriptsFolderRenamed:"Folder renamed",scriptsFolderDeleted:"Folder deleted; scripts moved to Ungrouped",scriptsFolderFailed:"Folder action failed: {message}",scriptsMoveToFolder:"Move to folder",quickFolderVisibility:"Folders shown",quickFolderAll:"Show all folders",quickViewResult:"View result",scriptsViewResult:"View result",scriptsFolderAdd:"Add folder",scriptsFolderScope:"Current folder",scriptsFolderAdded:"Folder “{name}” added",scriptsMoveUp:"Move up",scriptsMoveDown:"Move down",scriptsCopy:"Duplicate",scriptsCopied:"Saved a copy as {name}",scriptsCopyFailed:"Could not duplicate the script: {message}",scriptsResultTitle:"Run result",scriptsResultClose:"Close result",scriptsResultRunning:"Running · {steps} steps",scriptsResultDone:"Finished · {steps} steps",scriptsEditorEmpty:"Pick a script on the left, or press “+ New” to start one.",scriptsFolderEmpty:"No scripts in this folder yet — press “+ New” on the left.",scriptsRunCollapsed:"Run finished · {steps} steps",scriptsRunExpand:"Show result",scriptsRunCollapse:"Hide result",quickScriptsShow:"⚡ Quick scripts",quickScriptsHide:"Hide",quickScriptsManage:"Manage",quickScriptsEmpty:"No scripts yet. Create one in the Scripts panel and it appears here.",quickScriptsLoadFailed:"Could not load scripts",quickScriptsNoSession:"Connect a session before running a quick script",quickScriptsDone:"Ran {name}",quickScriptsPartial:"{name} ran; {failed} target(s) failed",quickScriptsFailed:"{name} failed: {message}",scriptsValidateAt:"{path} · {message}",scriptsValidateMore:"{count} more issue(s)",tplSend:"Send command",tplDelay:"Delay",tplSet:"Set variable",tplIf:"Conditional (if)",tplLoop:"Loop",tplExpect:"Assertion (expect)",tplLog:"Log line",kindSend:"send",kindDelay:"delay",kindSet:"set",kindLog:"log",kindExpect:"expect",kindIf:"if",kindLoop:"loop",kindUnknown:"unknown",vStepObject:"A step must be a JSON object",vNoKind:"The step has no kind (send/delay/set/log/expect/if/loop)",vMultiKind:"A step may only use one kind, got: {kinds}",vUnknownKind:"Unknown step kind: {kind}",vSend:"send must be a non-empty string",vDelay:"delay must be a positive number of milliseconds",vSetName:"a set variable name must match [A-Za-z_][A-Za-z0-9_]{0,31}",vSetValue:"set.value must be a string",vLog:"log must be a string",vExpect:"expect needs a condition object",vExpectOnFail:"expect.onFail must be stop or continue",vIfThen:"if needs a then step array",vIfThenEmpty:"if.then must not be empty",vIfElse:"if.else must be a step array",vLoopBody:"loop needs a steps array",vLoopCond:"loop needs at least one of count / while / until",vLoopCount:"loop.count must be an integer between 1 and 1000",vLoopMax:"loop.maxIterations must be an integer between 1 and 1000",vCondition:"a condition must be one of always/match/contains/variable/not/all/any",vConditionList:"{key} must be a non-empty array of conditions",vConditionRegex:"invalid regular expression",vConditionDeep:"Conditions nest deeper than the limit of {max} levels",vSteps:"steps must be an array of steps",vTooDeep:"Nesting exceeds the limit of {max} levels",vTooMany:"The script exceeds the limit of {max} steps"};function I(e,t,i){let s;try{s=e(t)}catch{s=t}if(typeof s!="string"&&(s=t),!i)return s;for(let[r,n]of Object.entries(i))s=s.split("{"+r+"}").join(String(n));return s}function oe(e){return e&&typeof e.message=="string"&&e.message?e.message:typeof e=="string"&&e?e:"Unknown error"}function Ho(e,t){let i=t&&typeof t.code=="string"?t.code:"";return i==="MISSING_SECRET"?e("errMissingSecret"):i==="AI_SECRET_DENIED"?e("errAiSecretDenied"):i==="PROFILE_NOT_FOUND"?e("errProfileNotFound"):oe(t)}var Le=require("react");var $i="/aiterm",Rs=class extends Error{constructor(t,i){super(t),this.name="ApiError",this.code=i}},Wo=()=>{};function zo(e){Wo=typeof e=="function"?e:()=>{}}function Pr(){try{let e=Wo();return typeof e=="string"&&e.length>0?e:void 0}catch{return}}function zc(e){return/^(sessions|permission|lock|read|audit)\./.test(e)||e==="history.sessions"||e==="history.query"||e==="batch.run"}function $c(e,t){let i=t!==null&&typeof t=="object"?t:{};if(!zc(e))return i;let s=Pr();return s===void 0?i:{...i,owner:s}}async function pe(e,t={}){let i;try{i=await fetch($i+"/rpc",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({method:e,params:$c(e,t)})})}catch(o){throw new Rs(o&&o.message?o.message:"network error","NETWORK_ERROR")}let s=null;try{s=await i.json()}catch{s=null}if(s&&typeof s=="object"&&s.ok===!0)return s.result;let r=s&&typeof s=="object"&&s.error&&typeof s.error=="object"?s.error:null,n=r&&typeof r.message=="string"?r.message:`HTTP ${i.status} ${i.statusText||""}`.trim();throw new Rs(n,r&&typeof r.code=="string"?r.code:void 0)}function Ds(e){if(typeof e!="string"||e==="")return new Uint8Array(0);try{let t=atob(e),i=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)i[s]=t.charCodeAt(s);return i}catch{return new Uint8Array(0)}}function Bs(e){if(typeof e!="string"||e==="")return null;try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function ce(e){return typeof e=="string"&&e?e:void 0}function ge(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ve(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ir(e){let t=Ve(e)||{},i=t.aiAccess==="ro"||t.aiAccess==="wo"||t.aiAccess==="rw"?t.aiAccess:"rw",s=t.lockOwner==="ai"||t.lockOwner==="human"?t.lockOwner:null,r=ge(t.lockExpiresAt)??null,n=typeof t.humanWriteBlocked=="boolean"?t.humanWriteBlocked:s==="ai",o=typeof t.aiWriteBlocked=="boolean"?t.aiWriteBlocked:i==="ro"||s==="human";return{aiAccess:i,lockOwner:s,lockExpiresAt:r,humanWriteBlocked:n,aiWriteBlocked:o}}function Yt(e){let t=Ve(e);if(!t)return null;let i=ce(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh",r=t.state==="connecting"||t.state==="open"||t.state==="disconnected"||t.state==="closed"||t.state==="failed"?t.state:"connecting";return{id:i,title:ce(t.title)||i,transport:s,host:ce(t.host)||"",port:ge(t.port)??(s==="telnet"?23:22),username:ce(t.username)||"",profileId:ce(t.profileId),state:r,error:ce(t.error),generation:Kc(t.generation),disconnectedAt:ge(t.disconnectedAt),closeReason:ce(t.closeReason),reconnecting:t.reconnecting===!0,cols:ge(t.cols)??80,rows:ge(t.rows)??24,createdAt:ge(t.createdAt)??0,updatedAt:ge(t.updatedAt)??0,lastActivityAt:ge(t.lastActivityAt)??0,bytesIn:ge(t.bytesIn)??0,bytesOut:ge(t.bytesOut)??0,permission:Ir(t.permission)}}function Kc(e){let t=ge(e);return t===void 0||t<0?0:Math.trunc(t)}function $o(e,t){let i={id:String(e||"")};return typeof t=="string"&&t.trim()!==""&&(i.reason=t.trim()),pe("sessions.disconnect",i)}function Or(e,t={}){let i={id:String(e||"")},s=Ve(t)||{},r=ge(s.cols),n=ge(s.rows);return r!==void 0&&r>0&&(i.cols=Math.trunc(r)),n!==void 0&&n>0&&(i.rows=Math.trunc(n)),i}function Ko(e,t){return pe("sessions.reconnect",Or(e,t))}function Uc(e){let t=Ve(e);if(!t)return null;let i=ce(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh",r=t.authType==="password"||t.authType==="privateKey"||t.authType==="agent"||t.authType==="none"?t.authType:"none";return{id:i,name:ce(t.name)||i,transport:s,host:ce(t.host)||"",port:ge(t.port)??(s==="telnet"?23:22),username:ce(t.username)||"",authType:r,hasPassword:t.hasPassword===!0,hasPrivateKey:t.hasPrivateKey===!0,hasPassphrase:t.hasPassphrase===!0,folder:ce(t.folder)||"",order:ge(t.order)??0,createdAt:ge(t.createdAt)??0,updatedAt:ge(t.updatedAt)??0}}function Ls(){return pe("profiles.list",{})}function Nr(e){return pe("profiles.save",{profile:e})}function Uo(e,t){return pe("profiles.rename",{id:String(e||""),name:String(t||"")})}function qo(e,t){return pe("profiles.setFolder",{id:String(e||""),folder:typeof t=="string"?t:""})}function Vo(e){return pe("profiles.delete",{id:String(e||"")})}function As(e){let t=Ve(e)||{},i=Array.isArray(t.profiles)?t.profiles.map(Uc).filter(Boolean):[],s=new Map;for(let n of i){let o=Fr(n);o!==""&&s.set(o,(s.get(o)||0)+1)}if(Array.isArray(t.folders))for(let n of t.folders){let o=Ve(n);if(!o)continue;let l=ce(o.name);if(!l)continue;let h=ge(o.count);s.has(l)||s.set(l,h??0)}let r=[...s.entries()].map(([n,o])=>({name:n,count:o})).sort((n,o)=>n.name.localeCompare(o.name));return{profiles:i,folders:r}}function Fr(e){return e&&typeof e.folder=="string"?e.folder.trim():""}function jo(e,t={}){let i=Array.isArray(e)?e:[],s=Array.isArray(t.extraFolders)?t.extraFolders:[],r=new Map;for(let h of s)typeof h=="string"&&h.trim()!==""&&r.set(h.trim(),[]);for(let h of i){let a=Fr(h);r.has(a)||r.set(a,[]),r.get(a).push(h)}let n=[...r.keys()].filter(h=>h!=="");n.sort((h,a)=>h.localeCompare(a));let o=[];for(let h of n){let a=r.get(h)||[];a.length===0&&t.keepEmpty!==!0||o.push({folder:h,items:a,count:a.length})}let l=r.get("")||[];return l.length>0&&o.push({folder:"",items:l,count:l.length}),o}function Yo(e={}){let t=e.transport==="telnet"?"telnet":"ssh",i={name:typeof e.name=="string"?e.name.trim():"",transport:t,host:typeof e.host=="string"?e.host.trim():"",port:ge(e.port)??(t==="telnet"?23:22),username:typeof e.username=="string"?e.username.trim():"",authType:t==="ssh"?e.authType==="privateKey"||e.authType==="agent"||e.authType==="none"?e.authType:"password":"none",folder:Fr(e)},s=ce(e.id);s&&(i.id=s);let r=ge(e.order);return r!==void 0&&(i.order=r),typeof e.password=="string"&&e.password!==""&&(i.password=e.password),typeof e.privateKey=="string"&&e.privateKey.trim()!==""&&(i.privateKey=e.privateKey),typeof e.passphrase=="string"&&e.passphrase!==""&&(i.passphrase=e.passphrase),i}function Hr(e){let t=Ve(e);if(!t)return null;let i=t.action==="read"||t.action==="write"||t.action==="deny"||t.action==="lock"?t.action:"read";return{at:ge(t.at)??Date.now(),sessionId:ce(t.sessionId),source:t.source==="ai"?"ai":"human",action:i,detail:ce(t.detail)||"",byteLength:ge(t.byteLength)??0}}function li(e){let t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;return t<1024?String(t):t<1024*1024?`${(t/1024).toFixed(1)}K`:`${(t/(1024*1024)).toFixed(1)}M`}function zi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Mr(e){return typeof e=="string"&&e!==""?e:void 0}function Go(e,t={}){let i={id:e,changedOnly:t.changedOnly===!0},s=zi(t.maxLines);return s!==void 0&&(i.maxLines=s),pe("read.screen",i)}function Xo(e={}){let t={},i=zi(e.limit);i!==void 0&&(t.limit=i);let s=zi(e.since);s!==void 0&&(t.since=s);let r=zi(e.until);return r!==void 0&&(t.until=r),pe("history.sessions",t)}function Jo(e={}){return pe("history.export",e)}function Zo(){return pe("autolog.get",{})}function Qo(e={}){return pe("autolog.set",e)}function ea(e={}){let t={},i=Mr(e.sessionId);i!==void 0&&(t.sessionId=i);for(let r of["since","until","context","maxMatches","maxBytes","limit"]){let n=zi(e[r]);n!==void 0&&(t[r]=n)}let s=Mr(e.search);return s!==void 0&&(t.search=s),pe("history.query",t)}function Ms(){return pe("scripts.list",{})}function Ps(e){return pe("scripts.get",{name:String(e||"")})}function Is(e){return pe("scripts.save",{script:e})}function ta(e){return pe("scripts.delete",{name:e})}function Os(e={}){let t={name:String(e.name||"")},i=Ve(e.params);i&&(t.params=i);let s=Array.isArray(e.targets)?e.targets.filter(r=>typeof r=="string"&&r!==""):[];if(s.length>0)t.targets=s;else{let r=Mr(e.sessionId);r!==void 0&&(t.sessionId=r)}return pe("scripts.run",t)}function Ts(e){let t=Ve(e);if(!t)return null;let i=ce(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh";return{id:i,title:ce(t.title)||i,transport:s,host:ce(t.host)||"",port:ge(t.port)??(s==="telnet"?23:22),username:ce(t.username)||"",createdAt:ge(t.createdAt)??0,closedAt:ge(t.closedAt),bytes:ge(t.bytes)??0,lastTs:ge(t.lastTs)??0}}function qc(e){let t=Ve(e);if(!t)return null;let i=s=>Array.isArray(s)?s.filter(r=>typeof r=="string"):[];return{at:ge(t.at)??0,line:typeof t.line=="string"?t.line:"",before:i(t.before),after:i(t.after)}}function ia(e){let t=Ve(e)||{},i=Array.isArray(t.matches)?t.matches.map(qc).filter(Boolean):[];return i.sort((s,r)=>s.at-r.at),{matches:i,text:typeof t.text=="string"?t.text:"",truncated:t.truncated===!0,scannedBytes:ge(t.scannedBytes)??0,entry:Ts(t.entry),sessions:Array.isArray(t.sessions)?t.sessions.map(Ts).filter(Boolean):void 0}}function sa(e){let t={};if(Array.isArray(e)){for(let s of e)if(typeof s=="string"&&s!=="")t[s]={};else if(s&&typeof s=="object"){let r=ce(s.name);r&&(t[r]={},typeof s.default=="string"&&(t[r].default=s.default),typeof s.description=="string"&&(t[r].description=s.description))}return t}let i=Ve(e);if(!i)return t;for(let[s,r]of Object.entries(i))if(s)if(typeof r=="string")t[s]={default:r};else if(Ve(r)){let n={};typeof r.default=="string"&&(n.default=r.default),typeof r.description=="string"&&(n.description=r.description),t[s]=n}else t[s]={};return t}function xi(e){let t=Ve(e);if(!t)return null;let i=ce(t.name);if(!i)return null;let s=sa(t.params),r=typeof t.params=="number"?ge(t.params):void 0,n=ge(t.stepCount)??(Array.isArray(t.steps)?t.steps.length:0);return{name:i,description:ce(t.description)||"",folder:ce(t.folder)||"",params:s,paramCount:r??Object.keys(s).length,stepCount:n,updatedAt:ge(t.updatedAt)??0}}function Ns(e){let t=Ve(e);if(!t)return null;let i=ce(t.name);return i?{name:i,description:typeof t.description=="string"?t.description:"",folder:typeof t.folder=="string"?t.folder:"",params:sa(t.params),steps:Array.isArray(t.steps)?t.steps:[]}:null}function Vc(e){let t=Ve(e);if(!t)return null;let i=Array.isArray(t.steps)?t.steps.map(s=>{let r=Ve(s)||{};return{index:ge(r.index)??0,depth:Math.max(0,ge(r.depth)??0),path:ce(r.path)||"",kind:ce(r.kind)||"",ok:r.ok===!0,matched:r.matched===!0,text:ce(r.text),cursor:ce(r.cursor),error:ce(r.error)}}):[];return{sessionId:ce(t.sessionId)||"",ok:t.ok===!0,steps:i,stoppedAt:ge(t.stoppedAt)}}function ra(e){let t=Ve(e)||{},i=Array.isArray(t.runs)?t.runs.map(Vc).filter(Boolean):[];return{ok:t.ok===!0,timedOut:t.timedOut===!0,label:ce(t.label),runs:i}}function na(e){let t=Ve(e);if(!t||t.type!=="batch")return null;let i=ce(t.batchId);return i?{batchId:i,label:ce(t.label),state:t.state==="done"?"done":"step",sessionId:ce(t.sessionId)||"",stepIndex:ge(t.stepIndex)??0,depth:Math.max(0,ge(t.depth)??0),path:ce(t.path)||"",kind:ce(t.kind)||"",ok:t.ok===!0,text:typeof t.text=="string"?t.text:void 0,error:ce(t.error),code:ce(t.code)}:null}function oa(e){let t=Ve(e)||{};return{text:typeof t.text=="string"?t.text:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(i=>typeof i=="string"):[],cursor:ce(t.cursor)||"",atPrompt:t.atPrompt===!0,unchanged:t.unchanged===!0}}var jc=/^(\d{1,9})\s*(s|m|h|d)$/i;function Wr(e,t=Date.now()){let i=typeof e=="string"?e.trim():"";if(i==="")return{ok:!0,at:void 0};let s=jc.exec(i);if(s){let n=Number(s[1]),o=s[2].toLowerCase(),l=o==="s"?1e3:o==="m"?6e4:o==="h"?36e5:864e5;return Number.isFinite(n)?{ok:!0,at:t-n*l}:{ok:!1}}if(/^\d{10,16}$/.test(i)){let n=Number(i);return Number.isFinite(n)?{ok:!0,at:i.length===10?n*1e3:n}:{ok:!1}}let r=Date.parse(i);return Number.isFinite(r)?{ok:!0,at:r}:{ok:!1}}function zt(e,t=2){return String(e).padStart(t,"0")}function zr(e){let t=typeof e=="number"&&Number.isFinite(e)?e:0,i=new Date(t);return Number.isNaN(i.getTime())?"--:--:--.---":`${zt(i.getHours())}:${zt(i.getMinutes())}:${zt(i.getSeconds())}.${zt(i.getMilliseconds(),3)}`}function $r(e,t=Date.now()){let i=typeof e=="number"&&Number.isFinite(e)?e:0,s=new Date(i);if(Number.isNaN(s.getTime()))return"—";let r=new Date(t),n=s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate(),o=`${zt(s.getHours())}:${zt(s.getMinutes())}:${zt(s.getSeconds())}`;return n?o:`${zt(s.getMonth()+1)}-${zt(s.getDate())} ${o.slice(0,5)}`}function Kr(e){return String(e??"").replace(/\s+/gu," ").trim()}function Ur(e,t){let i=qr(e),s=typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):200;return i.length>s?`${i.slice(0,Math.max(0,s-1))}…`:i}function qr(e){if(typeof e=="string")return e;if(e==null)return"";try{return String(e)}catch{return""}}function aa(e){let t=typeof e=="string"?e.trim():"";if(t==="")return null;try{return new RegExp(t,"gi")}catch{try{return new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi")}catch{return null}}}function la(e){let t=typeof e=="string"?e.trim():"";if(t!=="")try{return new RegExp(t),t}catch{return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}function ha(e,t){let i=qr(e);if(!t)return[{text:i,hit:!1}];let s;try{s=new RegExp(t.source,t.flags.includes("g")?t.flags:`${t.flags}g`)}catch{return[{text:i,hit:!1}]}let r=[],n=0,o=0,l=null;for(;(l=s.exec(i))!==null&&(o+=1,!(o>1e3));){if(l[0]===""){if(s.lastIndex+=1,s.lastIndex>i.length&&n>=i.length)break;continue}l.index>n&&r.push({text:i.slice(n,l.index),hit:!1}),r.push({text:l[0],hit:!0}),n=l.index+l[0].length}return n<i.length&&r.push({text:i.slice(n),hit:!1}),r.length>0?r:[{text:i,hit:!1}]}async function Fs(e,t){let i=qr(e);if(i==="")return!1;try{if(typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(i),!0}catch{}if(!t||typeof document>"u"||typeof document.createElement!="function")return!1;let s=null;try{s=document.createElement("textarea"),s.value=i,s.setAttribute("readonly","readonly"),s.style.position="absolute",s.style.left="-9999px",s.style.top="0",s.style.opacity="0",t.appendChild(s),s.focus(),s.select();let r=typeof document.execCommand=="function"?document.execCommand("copy")===!0:!1;return t.removeChild(s),r}catch{try{s&&s.parentNode&&s.parentNode.removeChild(s)}catch{}return!1}}var ua=require("react");var Yc=500;function Ei(){return{batchId:null,label:null,state:"idle",startedAt:0,lines:[],runs:null,error:null,pending:!1}}var qi=Object.freeze({kind:"terminal"}),Gc=["history","scripts","profiles"],Xc={sessions:[],selectedId:null,view:"terminal",resets:{},connectDraft:null,viewStack:[qi],panel:null,highlightProfileId:null,ready:!1,transportError:null,toast:null,audit:{},owner:void 0,batch:Ei()},ae=Xc,Vr=new Set,Gt=0,Hs=new Map,ca=0;function jr(e,t,i){let s=Hs.get(e.id);Hs.set(e.id,e.generation);let r=ae.resets[e.id],n=s!==void 0&&e.generation>s;return!i&&!n||r&&e.generation<=r.generation?null:(ca+=1,{seq:ca,generation:e.generation,reason:typeof t=="string"&&t?t:null,at:Date.now()})}function fa(e,t){let i=e.findIndex(s=>s.id===t.id);return i>=0?(e[i]=t,e):(e.push(t),e)}function pa(e,t,i){return t?{...i,resets:{...ae.resets,[e.id]:t}}:i}function Ws(){return ae}function Jc(e){return Vr.add(e),()=>{Vr.delete(e)}}function Qe(e){let t=typeof e=="function"?e(ae):e;ae={...ae,...t};for(let i of[...Vr])try{i()}catch(s){console.error("[aiterm] state listener failed",s)}}function Bt(){return(0,ua.useSyncExternalStore)(Jc,Ws,Ws)}function _a(e){let t=Array.isArray(e)?e.map(Yt).filter(Boolean):[],i=new Set(t.map(n=>n.id)),s={};for(let n of Object.keys(ae.resets))i.has(n)&&(s[n]=ae.resets[n]);for(let n of t){let o=jr(n,void 0,!1);o&&(s[n.id]=o)}for(let n of[...Hs.keys()])i.has(n)||Hs.delete(n);let r=ae.selectedId&&t.some(n=>n.id===ae.selectedId)?ae.selectedId:t.length>0?t[0].id:null;Qe({sessions:t,selectedId:r,ready:!0,transportError:null,resets:s})}function Lt(e){let t=Yt(e);if(!t)return null;let i=jr(t,void 0,!1),s=fa(ae.sessions.slice(),t),r=ae.selectedId??t.id;return Qe(pa(t,i,{sessions:s,selectedId:r,ready:!0})),t}function Yr(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},i=Yt(t.session);if(!i)return null;let s=jr(i,t.reason,!0),r=fa(ae.sessions.slice(),i),n=ae.selectedId??i.id;return Qe(pa(i,s,{sessions:r,selectedId:n,ready:!0})),s}function ma(e){return ae.resets[e]||null}var ga=new Map;function Gr(e,t,i){if(!e)return;let s=Number(t),r=Number(i);!Number.isFinite(s)||!Number.isFinite(r)||s<1||r<1||ga.set(String(e),{cols:Math.trunc(s),rows:Math.trunc(r)})}function va(e){return ga.get(String(e||""))||null}function Vi(e,t){if(!t)return;let i=Ir(t),s=ae.sessions.map(r=>r.id===e?{...r,permission:i}:r);Qe({sessions:s})}function Ri(e,t){let i=ae.sessions.map(s=>s.id===e?{...s,state:"closed",error:t||s.error}:s);Qe({sessions:i})}function ya(e,t={}){let i=e.length>0?e:[qi],s=i[i.length-1];return{viewStack:i,view:s.kind==="connect"?"connect":"terminal",panel:s.kind==="panel"?s.name:null,connectDraft:s.kind==="connect"&&s.draft||null,...t}}function zs(e,t={}){Qe(ya(e,t))}function Ki(){return ae.viewStack[ae.viewStack.length-1]||qi}function Sa(){return ae.viewStack.length>1}function Xr(){if(ae.viewStack.length<=1)return null;let e=Ki();return zs(ae.viewStack.slice(0,-1)),e}function hi(e){Qe(ya([qi],{selectedId:e,highlightProfileId:null}))}function Ti(e){let t=e&&typeof e=="object"&&typeof e.id=="string"&&e.id?e:null,i=ae.viewStack.slice(),s=i[i.length-1],r=s.kind==="connect"&&s.draft&&s.draft.id?s.draft.id:null,n=t?t.id:null;s.kind==="connect"&&r===n||(s.kind==="connect"&&i.pop(),i.push({kind:"connect",draft:t}),zs(i,{highlightProfileId:null}))}function Jr(e){if(Ki().kind!=="connect")return null;let t=ae.viewStack.slice(0,-1),i=typeof e=="string"&&e?e:ae.highlightProfileId;return zs(t,{highlightProfileId:i||null}),Ki()}function $s(e){if(e==null||!Gc.includes(e)){ci();return}if(!ae.selectedId&&e==="profiles")return;let t=Ki();if(t.kind==="panel"&&t.name===e)return;let i=ae.viewStack.slice();i[i.length-1].kind!=="terminal"&&i.pop(),i.push({kind:"panel",name:e,sessionId:ae.selectedId}),zs(i)}function ci(){return Ki().kind!=="panel"?null:Xr()}function ba(e){let t=typeof e=="string"&&e?e:null;ae.highlightProfileId!==t&&Qe({highlightProfileId:t})}function wa(e){Qe({batch:{...Ei(),label:typeof e=="string"&&e?e:null,state:"running",startedAt:Date.now(),pending:!0}})}function Zr(e={}){let t=ae.batch,i=e.result===void 0||e.result===null?t.runs:ra(e.result),s=typeof e.error=="string"&&e.error?e.error:null;Qe({batch:{...t,state:"done",pending:!1,runs:i,error:s}})}function Zc(e){let t=na(e);if(!t)return;let i=ae.batch;if(t.state==="done"){if(i.batchId&&i.batchId!==t.batchId)return;Qe({batch:{...i,batchId:i.batchId||t.batchId,label:i.label||t.label||null,state:"done",pending:!1}});return}let s=i,r=i.batchId!==null&&i.batchId!==t.batchId;i.state!=="running"||r?s={...Ei(),batchId:t.batchId,label:t.label||null,state:"running",startedAt:Date.now()}:i.batchId||(s={...i,batchId:t.batchId,label:i.label||t.label||null});let n={key:`${t.batchId}:${t.sessionId}:${t.stepIndex}:${s.lines.length}`,batchId:t.batchId,sessionId:t.sessionId,stepIndex:t.stepIndex,depth:t.depth,path:t.path,kind:t.kind,ok:t.ok,text:t.text,error:t.error,code:t.code,at:Date.now()};Qe({batch:{...s,lines:s.lines.concat(n).slice(-Yc)}})}function G(e){e&&(Qe({toast:{text:e,id:Date.now()+Math.random()}}),Gt&&clearTimeout(Gt),Gt=setTimeout(()=>{Gt=0,Qe({toast:null})},3500),typeof Gt=="object"&&Gt&&typeof Gt.unref=="function"&&Gt.unref())}function da(e){ae.transportError!==(e||null)&&Qe({transportError:e||null})}function Ca(e,t){if(!e)return;let i=Array.isArray(t)?t.map(Hr).filter(Boolean):[];Qe({audit:{...ae.audit,[e]:i.slice(-200)}})}function xa(e,t){let i=Hr(t);if(!i||i.sessionId&&i.sessionId!==e)return;let r=(ae.audit[e]||[]).concat({...i,sessionId:i.sessionId||e});Qe({audit:{...ae.audit,[e]:r.slice(-200)}})}function Ks(e){let t=typeof e=="string"&&e.length>0?e:void 0;if(t===ae.owner)return;let i=ki>0;if(i&&Xt){try{Xt.close()}catch{}Xt=null}Qe({owner:t,sessions:[],selectedId:null,ready:!1,viewStack:[qi],panel:null,batch:Ei(),connectDraft:null,highlightProfileId:null}),i&&(ki-=1,Qr()),Ui().catch(()=>{})}async function Ui(){let e=await pe("sessions.list",{});return _a(e?e.sessions:[]),ae.sessions}zo(()=>ae.owner);var Xt=null,ki=0;function Qr(){if(ki+=1,Xt||typeof EventSource>"u")return;let e;try{let t=ae.owner,i=typeof t=="string"&&t.length>0?`?owner=${encodeURIComponent(t)}`:"";e=new EventSource($i+"/events"+i)}catch{return}Xt=e,e.onmessage=t=>{let i=Bs(t.data);if(i){if(i.type==="sessions")_a(i.sessions);else if(i.type==="state")Lt(i.session);else if(i.type==="reset")try{Yr(i)}catch(s){console.error("[aiterm] reset frame failed",s)}else if(i.type==="batch")try{Zc(i)}catch(s){console.error("[aiterm] batch frame failed",s)}}},e.onopen=()=>{da(null),ae.ready||Ui().catch(()=>{})},e.onerror=()=>{da("stream"),ae.ready||Ui().catch(()=>{})}}function ka(){if(ki=Math.max(0,ki-1),!(ki>0||!Xt)){try{Xt.close()}catch{}Xt=null}}var mt=require("react");/**
|
|
11
|
+
var Jr=Object.defineProperty;var Fh=Object.getOwnPropertyDescriptor;var Hh=Object.getOwnPropertyNames;var Wh=Object.prototype.hasOwnProperty;var zh=(e,t)=>{for(var i in t)Jr(e,i,{get:t[i],enumerable:!0})},$h=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Hh(t))!Wh.call(e,r)&&r!==i&&Jr(e,r,{get:()=>t[r],enumerable:!(s=Fh(t,r))||s.enumerable});return e};var Kh=e=>$h(Jr({},"__esModule",{value:!0}),e);var T_={};zh(T_,{TAB_ID:()=>Vr,TAB_KIND:()=>jr,apply:()=>L_,inject:()=>R_});module.exports=Kh(T_);var ns="aiterm",Zo={title:"aiterm",guide:"连接 SSH 或 Telnet 服务器,与 AI 协同操作同一个终端",sessions:"会话",newSession:"新建会话",noSessions:"暂无终端会话",noSessionsHint:"新建一个 SSH 或 Telnet 连接开始使用;AI 也可以在这里创建会话。",loading:"加载中…",stateConnecting:"连接中",stateOpen:"已连接",stateDisconnected:"已断开",stateClosed:"已关闭",stateFailed:"连接失败",stateUnknown:"未知",connectTitle:"新建连接",transport:"协议",profile:"配置",profileManual:"手动填写",profileLoading:"正在读取配置…",profileEmpty:"暂无保存的配置",profileLoadFailed:"读取配置失败:{message}",host:"主机",port:"端口",username:"用户名",authType:"认证方式",authPassword:"密码",authPrivateKey:"私钥",authAgent:"SSH Agent",authNone:"无",password:"密码",passwordHint:"密码只用于建立连接,不会回显,也不会写进会话记录。",profileUsesSavedSecret:"将使用该配置中保存的凭据;留空即可。",profileNeedsSecretHint:"该配置没有保存密码,请在上方填写;勾选「保存为配置」可下次免填。",errMissingSecret:"这条配置里没有保存密码或私钥,请在上方填写后再连接。",errAiSecretDenied:"AI 不能代替你提供密码或私钥;请改用已保存凭据的配置,或由你手动连接。",errProfileNotFound:"这条配置已不存在(可能已被删除),刷新后重试。",privateKey:"私钥(PEM)",privateKeyHint:"粘贴 PEM 私钥内容;可留空表示使用配置中保存的私钥。",passphrase:"私钥口令",saveProfile:"保存为配置",profileName:"配置名称",connectAction:"连接",connectingAction:"正在连接…",cancel:"取消",permission:"AI 权限",permRo:"只读",permWo:"只写",permRw:"读写",permRoHint:"AI 只读:可以查看终端输出,但不能输入",permWoHint:"AI 只写:可以向终端输入,但不能读取输出",permRwHint:"AI 读写:可以输入并读取终端输出",lockAi:"AI 控制中",lockHuman:"人工接管中",lockFree:"空闲",lockAiCountdown:"{seconds}s 后自动释放",takeOver:"接管",releaseAi:"交还 AI",takeOverFailed:"接管失败:{message}",releaseFailed:"交还失败:{message}",accessFailed:"切换 AI 权限失败:{message}",blockedTitle:"AI 正在操作,人工输入已锁定",blockedHint:"接管后即可自行输入;AI 的输入会被拒绝。",takeOverInline:"立即接管",audit:"审计",auditEmpty:"暂无审计记录",auditLoading:"正在读取审计记录…",auditRead:"读取",auditWrite:"写入",auditDeny:"拒绝",auditLock:"锁定",auditFailed:"读取审计记录失败:{message}",sourceAi:"AI",sourceHuman:"人工",close:"关闭",closeSession:"关闭会话",closeConfirm:"确认关闭",closeFailed:"关闭会话失败:{message}",closeHint:"关闭后远程连接会断开。",closedTitle:"连接已关闭",failedTitle:"连接失败",closedReason:"原因:{reason}",reconnect:"重新连接",reconnecting:"连接中断,正在重连…",linkOpen:"已连接",linkConnecting:"连接中",disconnect:"中断",disconnectHint:"中断连接但保留会话,可稍后重连",disconnectFailed:"中断连接失败:{message}",disconnectedNotice:"已断开连接;会话已保留,可随时重连",disconnectedTitle:"连接已断开",disconnectedHint:"会话仍保留;重连后屏幕会重置。断开期间输入与复制屏幕不可用。",reconnectAction:"重连",reconnectingAction:"重连中…",reconnectFailed:"重连失败:{message}",reconnected:"已重新连接",terminalResetNotice:"── 已重新连接 · 屏幕已重置 ──",copyScreenUnavailable:"会话已断开,无法复制屏幕文本",back:"返回",connectHint:"选择已保存的配置,或手动填写连接信息",closeSessionPrompt:"关闭会话「{title}」?",profilesDeletePrompt:"确认删除配置「{name}」?",profilesActionFailed:"配置操作失败:{message}",scriptsDeletePrompt:"删除脚本「{name}」?",statusSize:"{cols}×{rows}",statusBytes:"收 {in} / 发 {out}",sessionEnded:"远程会话已结束",sessionExited:"会话已退出({code})",inputFailed:"发送输入失败:{message}",inputOverflow:"输入过快,已丢弃部分内容",unknownError:"未知错误",errorHostRequired:"请填写主机地址",errorUsernameRequired:"SSH 连接需要用户名",errorPort:"端口必须是 1-65535 之间的数字",connectFailed:"连接失败:{message}",profileSaveFailed:"会话已建立,但保存配置失败:{message}",profileNameRequired:"请填写配置名称",takenOver:"已接管终端",released:"已交还 AI",accessChanged:"AI 权限已更新",copied:"已复制",history:"历史",historyTitle:"终端历史",historyPanelClose:"关闭历史",historySessionsTitle:"历史会话",historyLoadingSessions:"正在读取历史会话…",historySessionsEmpty:"暂无历史会话",historySessionsTruncated:"已显示 {shown} 条(共 {total} 条)。",historyLoadMore:"加载更多",historyStaleReload:"历史在翻页期间发生变化,已重新加载首页以避免漏项。",historySessionsLimitReached:"已到服务端单次来源上限({shown}/{total},历史总数可能高估);请缩小时间范围。",historySessionsFailed:"读取历史会话失败:{message}",historyOngoing:"进行中",historySince:"起始时间",historyUntil:"结束时间",historyTimeHint:"如 10m / 2h / 90s / ISO 时间,留空不限",historySearch:"关键字",historySearchHint:"正则或纯文本;正则无效时按文本匹配",historyContext:"上下文",historyQuery:"查询",historyQuerying:"查询中…",historyTimeInvalid:"时间格式无效:{value}",historyQueryFailed:"查询历史失败:{message}",historyNoMatches:"没有匹配的历史输出",historyNoMatchesHint:"调整时间范围或关键字后重试。",historyFragment:"未设置关键字,下面是该时间段的原始输出片段",historyNeedSession:"请先选择一个历史会话",historyFooter:"扫描 {size} · 结果 {count} 条",historyTruncated:"已达扫描上限,结果可能不完整",historyCopy:"复制结果",historyCopyFailed:"无法访问剪贴板,请手动复制",historyLogFileTitle:"日志文件",historyExportOne:"导出当前",historyExportAll:"导出全部",historyExportHint:"把当前会话的输出导出成文本文件(默认目录 {dir})",historyExportAllHint:"把本对话的所有终端(含已关闭)各导出一个文本文件",historyExportDone:"已导出 {count} 个文件",historyExportEmpty:"没有可导出的内容",historyExportWhere:"已写入 {dir}",historyExportLines:"{count} 行",historyExportSkipped:"有 {count} 个来源缺失或不可读,未导出:{sessions}",historyExportSkippedTitle:"已跳过 {count} 个来源",historyExportOmitted:"{count} 个 incarnation 未处理({reason},上限 {limit})",historyExportFailed:"导出失败:{message}",historyLegacyEntry:"旧历史(无归属)",historyLegacyBack:"返回本对话历史",historyLegacyHint:"升级前的历史文件没有归属信息:只有你能查看,AI 无法访问;查看/导出不会改写或删除旧文件。",historyLegacyLoading:"正在读取旧历史…",historyLegacyFailed:"读取旧历史失败:{message}",historyExportNeedsRestart:"当前 DSH 进程还不支持日志导出:重启 DSH 后可用(客户端已更新,宿主代码需重启加载)。",historyAutoLogLabel:"自动把每个会话写进日志文件",historyAutoLogOffHint:"默认关闭。开启后每个会话实时追加写入磁盘文件。",historyAutoLogLegacyReview:"旧版本曾开启自动写日志。该开关会记录所有对话的终端输出,升级后默认保持关闭;原设置和目录未被修改。请人工确认:打开开关表示继续启用,点「保持关闭」则明确关闭。",historyAutoLogLegacyKeepOff:"保持关闭",historyAutoLogLoading:"正在读取自动写日志设置…",historyAutoLogLoadFailed:"读取自动写日志设置失败:{message}",historyAutoLogLegacyPath:"旧设置目录:{dir}",historyAutoLogLegacyEnable:"确认并继续使用该目录",historyAutoLogWhere:"正在写入 {dir}",historyAutoLogOn:"已开启自动写日志",historyAutoLogOff:"已关闭自动写日志",historyAutoLogFailed:"切换失败:{message}",historyManualCopy:"手动复制",historyEmptyQuery:"选择会话后会自动查询;也可调整条件后点击“查询”。",scripts:"脚本",scriptsTitle:"脚本",scriptsPanelClose:"关闭脚本",scriptsLoading:"正在读取脚本…",scriptsEmpty:"暂无脚本",scriptsEmptyHint:"在下方粘贴 JSON 定义并保存,或让 AI 创建脚本。",scriptsListFailed:"读取脚本失败:{message}",scriptsParams:"参数",scriptsNoParams:"无需参数",scriptsTarget:"运行目标",scriptsTargetCurrent:"当前会话",scriptsTargetPicked:"选定会话",scriptsTargetPickedHint:"已勾选 {count} 个会话",scriptsTargetPickedEmpty:"请至少勾选一个会话",scriptsTargetAll:"全部会话",scriptsTargetAllHint:"对 {count} 个已打开的会话执行",scriptsTargetNoSessions:"当前没有已打开的会话",scriptsNewAction:"新建",scriptsNewMacro:"新建 · 逐行命令",scriptsNewJson:"新建 · 高级脚本",scriptsRun:"运行",scriptsRunning:"运行中…",scriptsRunFailed:"运行脚本失败:{message}",scriptsRunDone:"执行完成",scriptsRunTimedOut:"执行超时,已中止",scriptsRunSummary:"共 {runs} 个会话,{ok} 个成功",scriptsProgressEmpty:"运行后将在此显示每一步的结果",scriptsSave:"保存脚本",scriptsSaveHint:'粘贴脚本 JSON:{"name","description","params","steps"}',scriptsSaveReplaceHint:"保存会整体替换同名脚本,请补全 steps。",scriptsSaveAction:"保存",scriptsCancel:"取消",scriptsSaved:"脚本已保存",scriptsJsonInvalid:"JSON 解析失败:{message}",scriptsJsonObject:"脚本必须是 JSON 对象",scriptsDelete:"删除",scriptsDeleteConfirm:"确认删除",scriptsDeleted:"脚本已删除",scriptsDeleteFailed:"删除失败:{message}",scriptsEdit:"编辑",scriptsSteps:"{count} 步(含嵌套)",scriptsParamsCount:"{count} 个参数",scriptsGroupCount:"{count} 个脚本",scriptsGetFailed:"读取脚本失败:{message}",scriptsGetInvalid:"读取脚本失败:Host 未返回脚本定义",scriptsLoadingEditor:"正在读取脚本…",scriptsEmptySaveWarn:"该脚本原有 {count} 个步骤,当前 steps 为空;再次点击“仍要保存空脚本”才会保存。",scriptsEmptySaveConfirm:"仍要保存空脚本",copyScreen:"复制当前屏幕文本",copyScreenDone:"屏幕文本已复制",copyScreenEmpty:"当前屏幕没有文本",copyScreenFailed:"复制屏幕文本失败:{message}",copyFailed:"无法访问剪贴板,请手动复制",profiles:"配置管理",profilesTitle:"配置管理",profilesPanelClose:"关闭配置管理",profilesLoading:"正在读取配置…",profilesEmpty:"暂无保存的配置",profilesEmptyHint:"新建连接时勾选“保存为配置”,或让 AI 帮你保存一个。",profilesListFailed:"读取配置失败:{message}",profilesFooter:"{profiles} 个配置 · {folders} 个分组",profilesReload:"刷新",profilesUngrouped:"未分组",profilesFolderCount:"{count} 个配置",profilesBadgePassword:"密码",profilesBadgePrivateKey:"私钥",profilesBadgePassphrase:"口令",profilesConnect:"连接",profilesEdit:"编辑",profilesRename:"重命名",profilesMove:"移动到分组",profilesDelete:"删除",profilesDeleteConfirm:"确认删除",profilesDeleteDone:"配置已删除",profilesDeleteFailed:"删除配置失败:{message}",profilesRenamed:"配置已重命名",profilesRenameFailed:"重命名失败:{message}",profilesMoved:"已移动分组",profilesMoveFailed:"移动分组失败:{message}",profilesNameRequired:"配置名称不能为空",profilesNamePlaceholder:"配置名称",profilesRenameSave:"保存",profilesRenameCancel:"取消",profilesNewConnection:"新建连接",profilesNewFolder:"新建分组",profilesNewFolderPlaceholder:"分组名称",profilesCreateFolder:"创建",profilesFolderAdded:"已创建分组“{name}”",profilesFolderNameRequired:"分组名称不能为空",profilesConnectFailed:"连接失败:{message}",profilesEditHint:"密钥类字段留空表示保留已保存的凭据;保存后可在配置管理中连接。",profilesEditTitle:"编辑配置",profilesSaveAction:"保存修改",profilesSaved:"配置已保存",profilesSaveFailed:"保存配置失败:{message}",folder:"分组",folderNone:"未分组",folderNew:"新建分组…",folderName:"分组名称",scriptsTemplate:"模板",scriptsNewType:"新建类型",scriptsTemplateCmd:"发送命令",scriptsTemplateWait:"等待(@wait)",scriptsTemplateSet:"设置变量(@set)",scriptsTemplateLog:"输出日志(@log)",scriptsTemplateExpect:"断言(@expect)",scriptsTemplatePlaceholder:"插入模板…",scriptsTemplateRebuilt:"当前 JSON 无法解析,已用模板重建脚本",scriptsUngrouped:"未分组",scriptsMode:"编写方式",scriptsModeMacro:"逐行命令",scriptsModeJson:"JSON(高级)",scriptsJsonHint:"完整的步骤数组,支持 if/loop 等高级结构。",scriptsMacroHint:"每行一条命令,直接发送;以 @ 开头是控制行。",scriptsMacroHelp:"示例:ls -l / @wait 500 / @wait 2s / @set name = value / @log 说明 / @expect 匹配文本 / @python … @end(发到远端 shell 里执行)",scriptsMacroWait:"每条命令发送后等它跑完(等输出停顿)",scriptsMacroWaitHint:"不勾选时命令会连续发出,可能还没回显就发送下一条。",scriptsMacroParseError:"第 {line} 行:{message}",scriptsMacroNoSteps:"至少写一条命令",scriptsMacroUnsupported:"这个脚本含 if/loop 等结构化步骤,只能在 JSON 模式编辑。",scriptsTemplatePython:"Python(远端执行)",quickScripts:"快捷脚本",scriptsName:"名称",scriptsNameHint:"同名脚本会被覆盖。",scriptsNameRequired:"请填写脚本名称",scriptsFolder:"分组",scriptsFolderCreate:"+ 新建分组…",scriptsFolderNew:"分组名",scriptsFolderUse:"使用",scriptsFolderRename:"重命名分组",scriptsFolderDelete:"删除分组",scriptsFolderDeletePrompt:"删除分组「{name}」?组内脚本会移到未分组。",scriptsFolderRenamed:"分组已重命名",scriptsFolderDeleted:"分组已删除,脚本已移到未分组",scriptsFolderFailed:"分组操作失败:{message}",scriptsMoveToFolder:"移到分组",quickFolderVisibility:"分组显示",quickFolderAll:"显示全部分组",quickViewResult:"查看结果",scriptsViewResult:"查看结果",scriptsFolderAdd:"添加分组",scriptsFolderScope:"当前分组",scriptsFolderAdded:"已添加分组「{name}」",scriptsMoveUp:"上移",scriptsMoveDown:"下移",scriptsCopy:"复制",scriptsCopied:"已复制为 {name}",scriptsCopyFailed:"复制脚本失败:{message}",scriptsResultTitle:"运行结果",scriptsResultClose:"关闭结果",scriptsResultRunning:"运行中 · {steps} 步",scriptsResultDone:"运行完成 · {steps} 步",scriptsEditorEmpty:"从左侧选择一个脚本,或点「+ 新建」开始编写。",scriptsFolderEmpty:"这个分组下还没有脚本,点左侧「+ 新建」添加。",scriptsRunCollapsed:"运行完成 · {steps} 步",scriptsRunExpand:"展开结果",scriptsRunCollapse:"收起结果",quickScriptsShow:"⚡ 快捷脚本",quickScriptsHide:"收起",quickScriptsManage:"管理",quickScriptsEmpty:"暂无脚本;在「脚本」面板里新建,保存后会出现在这里。",quickScriptsLoadFailed:"读取脚本失败",quickScriptsNoSession:"先连接一个会话再运行快捷脚本",quickScriptsDone:"已运行 {name}",quickScriptsPartial:"{name} 已运行,但有 {failed} 个目标失败",quickScriptsFailed:"{name} 运行失败:{message}",scriptsValidateAt:"{path} · {message}",scriptsValidateMore:"另有 {count} 处问题",tplSend:"发送命令",tplDelay:"延迟",tplSet:"设置变量",tplIf:"条件分支 (if)",tplLoop:"循环 (loop)",tplExpect:"断言 (expect)",tplLog:"输出日志",kindSend:"发送命令",kindDelay:"延迟",kindSet:"设置变量",kindLog:"输出日志",kindExpect:"断言",kindIf:"条件分支",kindLoop:"循环",kindUnknown:"未知",vStepObject:"步骤必须是 JSON 对象",vNoKind:"步骤缺少类型(send/delay/set/log/expect/if/loop 之一)",vMultiKind:"一个步骤不能同时包含多种类型:{kinds}",vUnknownKind:"未知步骤类型:{kind}",vSend:"send 必须是非空字符串",vDelay:"delay 必须是大于 0 的毫秒数",vSetName:"set 变量名必须匹配 [A-Za-z_][A-Za-z0-9_]{0,31}",vSetValue:"set.value 必须是字符串",vLog:"log 必须是字符串",vExpect:"expect 缺少条件对象",vExpectOnFail:"expect.onFail 只能是 stop 或 continue",vIfThen:"if 缺少 then 步骤数组",vIfThenEmpty:"if 的 then 不能为空",vIfElse:"if 的 else 必须是步骤数组",vLoopBody:"loop 缺少 steps 步骤数组",vLoopCond:"loop 需要 count / while / until 至少一个",vLoopCount:"loop.count 必须是 1-1000 之间的正整数",vLoopMax:"loop.maxIterations 必须是 1-1000 之间的正整数",vCondition:"条件必须是 always/match/contains/variable/not/all/any 之一",vConditionList:"{key} 必须是非空的条件数组",vConditionRegex:"正则表达式无效",vConditionDeep:"条件嵌套超过上限({max} 层)",vSteps:"steps 必须是步骤数组",vTooDeep:"嵌套深度超过上限({max} 层)",vTooMany:"步骤总数超过上限({max})"},Qo={title:"aiterm",guide:"Open an SSH or Telnet session and share the terminal with the AI",sessions:"Sessions",newSession:"New session",noSessions:"No terminal sessions yet",noSessionsHint:"Create an SSH or Telnet connection to get started. The AI can open sessions here too.",loading:"Loading…",stateConnecting:"Connecting",stateOpen:"Connected",stateDisconnected:"Disconnected",stateClosed:"Closed",stateFailed:"Failed",stateUnknown:"Unknown",connectTitle:"New connection",transport:"Protocol",profile:"Profile",profileManual:"Enter manually",profileLoading:"Loading profiles…",profileEmpty:"No saved profiles",profileLoadFailed:"Could not load profiles: {message}",host:"Host",port:"Port",username:"Username",authType:"Authentication",authPassword:"Password",authPrivateKey:"Private key",authAgent:"SSH agent",authNone:"None",password:"Password",passwordHint:"The password is used only to connect. It is never echoed or stored in the session log.",profileUsesSavedSecret:"The credentials saved in this profile are used; leave the field empty.",profileNeedsSecretHint:'This profile has no saved password — type it above. Tick "Save as profile" to skip it next time.',errMissingSecret:"This profile has no saved password or key — fill it in above, then connect.",errAiSecretDenied:"The AI may not supply a password or key for you. Use a profile with saved credentials, or connect manually.",errProfileNotFound:"This profile no longer exists (it may have been deleted). Refresh and try again.",privateKey:"Private key (PEM)",privateKeyHint:"Paste a PEM private key, or leave empty to use the key saved in the profile.",passphrase:"Key passphrase",saveProfile:"Save as profile",profileName:"Profile name",connectAction:"Connect",connectingAction:"Connecting…",cancel:"Cancel",permission:"AI access",permRo:"Read",permWo:"Write",permRw:"Read+write",permRoHint:"AI can read terminal output but cannot send input",permWoHint:"AI can send input but cannot read terminal output",permRwHint:"AI can send input and read terminal output",lockAi:"AI in control",lockHuman:"Human in control",lockFree:"Idle",lockAiCountdown:"auto-release in {seconds}s",takeOver:"Take over",releaseAi:"Hand back to AI",takeOverFailed:"Could not take over: {message}",releaseFailed:"Could not hand back: {message}",accessFailed:"Could not change AI access: {message}",blockedTitle:"The AI is using this terminal — human input is locked",blockedHint:"Take over to type. AI input is refused while you hold control.",takeOverInline:"Take over now",audit:"Audit",auditEmpty:"No audit entries",auditLoading:"Loading audit entries…",auditRead:"read",auditWrite:"write",auditDeny:"deny",auditLock:"lock",auditFailed:"Could not load audit entries: {message}",sourceAi:"AI",sourceHuman:"Human",close:"Close",closeSession:"Close session",closeConfirm:"Confirm close",closeFailed:"Could not close the session: {message}",closeHint:"Closing disconnects the remote connection.",closedTitle:"Connection closed",failedTitle:"Connection failed",closedReason:"Reason: {reason}",reconnect:"Reconnect",reconnecting:"Connection lost, reconnecting…",linkOpen:"Connected",linkConnecting:"Connecting",disconnect:"Disconnect",disconnectHint:"Disconnect but keep the session; reconnect later",disconnectFailed:"Could not disconnect: {message}",disconnectedNotice:"Disconnected — the session is kept and can be reconnected",disconnectedTitle:"Connection lost",disconnectedHint:"The session is kept. Reconnecting resets the screen. Input and screen copy stay disabled while disconnected.",reconnectAction:"Reconnect",reconnectingAction:"Reconnecting…",reconnectFailed:"Could not reconnect: {message}",reconnected:"Reconnected",terminalResetNotice:"── Reconnected · screen reset ──",copyScreenUnavailable:"The session is disconnected; screen text cannot be copied",back:"Back",connectHint:"Pick a saved profile, or enter the connection details",closeSessionPrompt:"Close session “{title}”?",profilesDeletePrompt:"Delete profile “{name}”?",profilesActionFailed:"Profile action failed: {message}",scriptsDeletePrompt:"Delete script “{name}”?",statusSize:"{cols}×{rows}",statusBytes:"in {in} / out {out}",sessionEnded:"The remote session ended",sessionExited:"Session exited ({code})",inputFailed:"Could not send input: {message}",inputOverflow:"Input was too fast; some keystrokes were dropped",unknownError:"Unknown error",errorHostRequired:"Enter a host",errorUsernameRequired:"SSH needs a username",errorPort:"The port must be a number between 1 and 65535",connectFailed:"Connection failed: {message}",profileSaveFailed:"Session opened, but saving the profile failed: {message}",profileNameRequired:"Enter a profile name",takenOver:"You now control the terminal",released:"Control handed back to the AI",accessChanged:"AI access updated",copied:"Copied",history:"History",historyTitle:"Terminal history",historyPanelClose:"Close history",historySessionsTitle:"History sessions",historyLoadingSessions:"Loading history sessions…",historySessionsEmpty:"No history sessions yet",historySessionsTruncated:"Showing {shown} of {total}.",historyLoadMore:"Load more",historyStaleReload:"History changed while paging; reloaded the first page to avoid skipping entries.",historySessionsLimitReached:"Server source limit reached ({shown}/{total}; legacy total may be overestimated); narrow the time window.",historySessionsFailed:"Could not load history sessions: {message}",historyOngoing:"active",historySince:"Since",historyUntil:"Until",historyTimeHint:"e.g. 10m / 2h / 90s / ISO time; empty means unbounded",historySearch:"Keyword",historySearchHint:"Regex or plain text; an invalid regex is matched literally",historyContext:"Context",historyQuery:"Search",historyQuerying:"Searching…",historyTimeInvalid:"Invalid time value: {value}",historyQueryFailed:"Could not query history: {message}",historyNoMatches:"No matching history output",historyNoMatchesHint:"Adjust the time range or keyword and try again.",historyFragment:"No keyword set — showing the raw output slice for this time range",historyNeedSession:"Select a history session first",historyFooter:"Scanned {size} · {count} matches",historyTruncated:"Scan cap reached; results may be incomplete",historyCopy:"Copy results",historyCopyFailed:"Clipboard unavailable — copy manually",historyLogFileTitle:"Log files",historyExportOne:"Export this",historyExportAll:"Export all",historyExportHint:"Write this session's output to a text file (default {dir})",historyExportAllHint:"Write one text file per terminal owned by this conversation, including closed ones",historyExportDone:"Exported {count} file(s)",historyExportEmpty:"Nothing to export",historyExportWhere:"Written to {dir}",historyExportLines:"{count} lines",historyExportSkipped:"{count} source(s) were missing/unreadable and not exported: {sessions}",historyExportSkippedTitle:"Skipped {count} source(s)",historyExportOmitted:"{count} incarnation(s) not attempted ({reason}, limit {limit})",historyExportFailed:"Export failed: {message}",historyLegacyEntry:"Legacy history (no owner)",historyLegacyBack:"Back to this conversation",historyLegacyHint:"Pre-upgrade files carry no owner. Only you can open them; the AI cannot. Viewing or exporting never rewrites or deletes the old files.",historyLegacyLoading:"Loading legacy history…",historyLegacyFailed:"Could not load legacy history: {message}",historyExportNeedsRestart:"This DSH process cannot export logs yet: restart DSH to load the Host half.",historyAutoLogLabel:"Write every session to a log file",historyAutoLogOffHint:"Off by default. When on, each session appends to a file on disk in real time.",historyAutoLogLegacyReview:"An older version enabled automatic log files. This switch records every conversation's terminal output, so it stays off after upgrade until you confirm; the old setting and directory were not modified. Turn it on to keep using it, or choose Keep off to confirm it stays disabled.",historyAutoLogLegacyKeepOff:"Keep off",historyAutoLogLoading:"Loading automatic log settings…",historyAutoLogLoadFailed:"Could not load automatic log settings: {message}",historyAutoLogLegacyPath:"Old configured directory: {dir}",historyAutoLogLegacyEnable:"Confirm and keep using this directory",historyAutoLogWhere:"Writing to {dir}",historyAutoLogOn:"Auto-log enabled",historyAutoLogOff:"Auto-log disabled",historyAutoLogFailed:"Could not switch: {message}",historyManualCopy:"Manual copy",historyEmptyQuery:"The selected session is queried automatically; adjust the filters and search again.",scripts:"Scripts",scriptsTitle:"Scripts",scriptsPanelClose:"Close scripts",scriptsLoading:"Loading scripts…",scriptsEmpty:"No scripts yet",scriptsEmptyHint:"Paste a JSON definition below and save it, or let the AI create one.",scriptsListFailed:"Could not load scripts: {message}",scriptsParams:"Parameters",scriptsNoParams:"No parameters",scriptsTarget:"Target",scriptsTargetCurrent:"This session",scriptsTargetPicked:"Pick sessions",scriptsTargetPickedHint:"{count} session(s) ticked",scriptsTargetPickedEmpty:"Tick at least one session",scriptsTargetAll:"All sessions",scriptsTargetAllHint:"Runs on {count} open sessions",scriptsTargetNoSessions:"There are no open sessions",scriptsNewAction:"New",scriptsNewMacro:"New · commands",scriptsNewJson:"New · advanced",scriptsRun:"Run",scriptsRunning:"Running…",scriptsRunFailed:"Could not run the script: {message}",scriptsRunDone:"Finished",scriptsRunTimedOut:"Timed out and aborted",scriptsRunSummary:"{runs} sessions, {ok} succeeded",scriptsProgressEmpty:"Step results appear here after a run",scriptsSave:"Save script",scriptsSaveHint:'Paste script JSON: {"name","description","params","steps"}',scriptsSaveReplaceHint:"Saving replaces the script with this JSON; include its steps.",scriptsSaveAction:"Save",scriptsCancel:"Cancel",scriptsSaved:"Script saved",scriptsJsonInvalid:"Invalid JSON: {message}",scriptsJsonObject:"The script must be a JSON object",scriptsDelete:"Delete",scriptsDeleteConfirm:"Confirm delete",scriptsDeleted:"Script deleted",scriptsDeleteFailed:"Could not delete: {message}",scriptsEdit:"Edit",scriptsSteps:"{count} steps (incl. nested)",scriptsParamsCount:"{count} params",scriptsGroupCount:"{count} scripts",scriptsGetFailed:"Could not load the script: {message}",scriptsGetInvalid:"Could not load the script: the Host returned no script definition",scriptsLoadingEditor:"Loading script…",scriptsEmptySaveWarn:"This script had {count} steps and steps is now empty; click “Save empty program” again to confirm.",scriptsEmptySaveConfirm:"Save empty program",copyScreen:"Copy screen text",copyScreenDone:"Screen text copied",copyScreenEmpty:"The screen is empty",copyScreenFailed:"Could not copy the screen text: {message}",copyFailed:"Clipboard unavailable — copy manually",profiles:"Profiles",profilesTitle:"Manage profiles",profilesPanelClose:"Close profiles",profilesLoading:"Loading profiles…",profilesEmpty:"No saved profiles",profilesEmptyHint:"Tick “Save as profile” when connecting, or let the AI save one for you.",profilesListFailed:"Could not load profiles: {message}",profilesFooter:"{profiles} profiles · {folders} folders",profilesReload:"Refresh",profilesUngrouped:"Ungrouped",profilesFolderCount:"{count} profiles",profilesBadgePassword:"password",profilesBadgePrivateKey:"key",profilesBadgePassphrase:"passphrase",profilesConnect:"Connect",profilesEdit:"Edit",profilesRename:"Rename",profilesMove:"Move to folder",profilesDelete:"Delete",profilesDeleteConfirm:"Confirm delete",profilesDeleteDone:"Profile deleted",profilesDeleteFailed:"Could not delete the profile: {message}",profilesRenamed:"Profile renamed",profilesRenameFailed:"Could not rename the profile: {message}",profilesMoved:"Profile moved",profilesMoveFailed:"Could not move the profile: {message}",profilesNameRequired:"A profile name is required",profilesNamePlaceholder:"Profile name",profilesRenameSave:"Save",profilesRenameCancel:"Cancel",profilesNewConnection:"New connection",profilesNewFolder:"New folder",profilesNewFolderPlaceholder:"Folder name",profilesCreateFolder:"Create",profilesFolderAdded:"Folder “{name}” created",profilesFolderNameRequired:"A folder name is required",profilesConnectFailed:"Could not connect: {message}",profilesEditHint:"Leave secret fields blank to keep the saved credentials; save, then connect from profiles.",profilesEditTitle:"Edit profile",profilesSaveAction:"Save changes",profilesSaved:"Profile saved",profilesSaveFailed:"Could not save the profile: {message}",folder:"Folder",folderNone:"Ungrouped",folderNew:"New folder…",folderName:"Folder name",scriptsTemplate:"Template",scriptsNewType:"Create as",scriptsTemplateCmd:"Send command",scriptsTemplateWait:"Wait (@wait)",scriptsTemplateSet:"Set variable (@set)",scriptsTemplateLog:"Log line (@log)",scriptsTemplateExpect:"Assert (@expect)",scriptsTemplatePlaceholder:"Insert template…",scriptsTemplateRebuilt:"The current JSON could not be parsed, so the script was rebuilt from the template",scriptsUngrouped:"Ungrouped",scriptsMode:"Editing mode",scriptsModeMacro:"One command per line",scriptsModeJson:"JSON (advanced)",scriptsJsonHint:"The full step array, including if/loop structures.",scriptsMacroHint:"Each line is sent as a command; lines starting with @ are directives.",scriptsMacroHelp:"Examples: ls -l / @wait 500 / @wait 2s / @set name = value / @log note / @expect pattern / @python … @end (runs on the remote shell)",scriptsMacroWait:"Wait for each command to finish (output goes idle)",scriptsMacroWaitHint:"Unchecked, lines are sent back to back and may race the prompt.",scriptsMacroParseError:"line {line}: {message}",scriptsMacroNoSteps:"Write at least one command",scriptsMacroUnsupported:"This script uses if/loop steps, so it can only be edited as JSON.",scriptsTemplatePython:"Python (remote)",quickScripts:"Quick scripts",scriptsName:"Name",scriptsNameHint:"An existing script with the same name is overwritten.",scriptsNameRequired:"Enter a script name",scriptsFolder:"Folder",scriptsFolderCreate:"+ New folder…",scriptsFolderNew:"Folder name",scriptsFolderUse:"Use",scriptsFolderRename:"Rename folder",scriptsFolderDelete:"Delete folder",scriptsFolderDeletePrompt:'Delete folder "{name}"? Its scripts move to Ungrouped.',scriptsFolderRenamed:"Folder renamed",scriptsFolderDeleted:"Folder deleted; scripts moved to Ungrouped",scriptsFolderFailed:"Folder action failed: {message}",scriptsMoveToFolder:"Move to folder",quickFolderVisibility:"Folders shown",quickFolderAll:"Show all folders",quickViewResult:"View result",scriptsViewResult:"View result",scriptsFolderAdd:"Add folder",scriptsFolderScope:"Current folder",scriptsFolderAdded:"Folder “{name}” added",scriptsMoveUp:"Move up",scriptsMoveDown:"Move down",scriptsCopy:"Duplicate",scriptsCopied:"Saved a copy as {name}",scriptsCopyFailed:"Could not duplicate the script: {message}",scriptsResultTitle:"Run result",scriptsResultClose:"Close result",scriptsResultRunning:"Running · {steps} steps",scriptsResultDone:"Finished · {steps} steps",scriptsEditorEmpty:"Pick a script on the left, or press “+ New” to start one.",scriptsFolderEmpty:"No scripts in this folder yet — press “+ New” on the left.",scriptsRunCollapsed:"Run finished · {steps} steps",scriptsRunExpand:"Show result",scriptsRunCollapse:"Hide result",quickScriptsShow:"⚡ Quick scripts",quickScriptsHide:"Hide",quickScriptsManage:"Manage",quickScriptsEmpty:"No scripts yet. Create one in the Scripts panel and it appears here.",quickScriptsLoadFailed:"Could not load scripts",quickScriptsNoSession:"Connect a session before running a quick script",quickScriptsDone:"Ran {name}",quickScriptsPartial:"{name} ran; {failed} target(s) failed",quickScriptsFailed:"{name} failed: {message}",scriptsValidateAt:"{path} · {message}",scriptsValidateMore:"{count} more issue(s)",tplSend:"Send command",tplDelay:"Delay",tplSet:"Set variable",tplIf:"Conditional (if)",tplLoop:"Loop",tplExpect:"Assertion (expect)",tplLog:"Log line",kindSend:"send",kindDelay:"delay",kindSet:"set",kindLog:"log",kindExpect:"expect",kindIf:"if",kindLoop:"loop",kindUnknown:"unknown",vStepObject:"A step must be a JSON object",vNoKind:"The step has no kind (send/delay/set/log/expect/if/loop)",vMultiKind:"A step may only use one kind, got: {kinds}",vUnknownKind:"Unknown step kind: {kind}",vSend:"send must be a non-empty string",vDelay:"delay must be a positive number of milliseconds",vSetName:"a set variable name must match [A-Za-z_][A-Za-z0-9_]{0,31}",vSetValue:"set.value must be a string",vLog:"log must be a string",vExpect:"expect needs a condition object",vExpectOnFail:"expect.onFail must be stop or continue",vIfThen:"if needs a then step array",vIfThenEmpty:"if.then must not be empty",vIfElse:"if.else must be a step array",vLoopBody:"loop needs a steps array",vLoopCond:"loop needs at least one of count / while / until",vLoopCount:"loop.count must be an integer between 1 and 1000",vLoopMax:"loop.maxIterations must be an integer between 1 and 1000",vCondition:"a condition must be one of always/match/contains/variable/not/all/any",vConditionList:"{key} must be a non-empty array of conditions",vConditionRegex:"invalid regular expression",vConditionDeep:"Conditions nest deeper than the limit of {max} levels",vSteps:"steps must be an array of steps",vTooDeep:"Nesting exceeds the limit of {max} levels",vTooMany:"The script exceeds the limit of {max} steps"};function D(e,t,i){let s;try{s=e(t)}catch{s=t}if(typeof s!="string"&&(s=t),!i)return s;for(let[r,n]of Object.entries(i))s=s.split("{"+r+"}").join(String(n));return s}function ne(e){return e&&typeof e.message=="string"&&e.message?e.message:typeof e=="string"&&e?e:"Unknown error"}function ea(e,t){let i=t&&typeof t.code=="string"?t.code:"";return i==="MISSING_SECRET"?e("errMissingSecret"):i==="AI_SECRET_DENIED"?e("errAiSecretDenied"):i==="PROFILE_NOT_FOUND"?e("errProfileNotFound"):ne(t)}var Ie=require("react");var as="/aiterm",js=class extends Error{constructor(t,i){super(t),this.name="ApiError",this.code=i}},ta=()=>{};function ia(e){ta=typeof e=="function"?e:()=>{}}function Zr(){try{let e=ta();return typeof e=="string"&&e.length>0?e:void 0}catch{return}}function Uh(e){return/^(sessions|permission|lock|read|audit)\./.test(e)||e==="history.sessions"||e==="history.query"||e==="history.export"||e==="batch.run"}function qh(e,t){let i=t!==null&&typeof t=="object"?t:{};if(!Uh(e))return i;let s=Zr();return s===void 0?i:{...i,owner:s}}async function ge(e,t={}){let i;try{i=await fetch(as+"/rpc",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({method:e,params:qh(e,t)})})}catch(o){throw new js(o&&o.message?o.message:"network error","NETWORK_ERROR")}let s=null;try{s=await i.json()}catch{s=null}if(s&&typeof s=="object"&&s.ok===!0)return s.result;let r=s&&typeof s=="object"&&s.error&&typeof s.error=="object"?s.error:null,n=r&&typeof r.message=="string"?r.message:`HTTP ${i.status} ${i.statusText||""}`.trim();throw new js(n,r&&typeof r.code=="string"?r.code:void 0)}function Ys(e){if(typeof e!="string"||e==="")return new Uint8Array(0);try{let t=atob(e),i=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)i[s]=t.charCodeAt(s);return i}catch{return new Uint8Array(0)}}function Gs(e){if(typeof e!="string"||e==="")return null;try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function me(e){return typeof e=="string"&&e?e:void 0}function be(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Xe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Qr(e){let t=Xe(e)||{},i=t.aiAccess==="ro"||t.aiAccess==="wo"||t.aiAccess==="rw"?t.aiAccess:"rw",s=t.lockOwner==="ai"||t.lockOwner==="human"?t.lockOwner:null,r=be(t.lockExpiresAt)??null,n=typeof t.humanWriteBlocked=="boolean"?t.humanWriteBlocked:s==="ai",o=typeof t.aiWriteBlocked=="boolean"?t.aiWriteBlocked:i==="ro"||s==="human";return{aiAccess:i,lockOwner:s,lockExpiresAt:r,humanWriteBlocked:n,aiWriteBlocked:o}}function li(e){let t=Xe(e);if(!t)return null;let i=me(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh",r=t.state==="connecting"||t.state==="open"||t.state==="disconnected"||t.state==="closed"||t.state==="failed"?t.state:"connecting";return{id:i,title:me(t.title)||i,transport:s,host:me(t.host)||"",port:be(t.port)??(s==="telnet"?23:22),username:me(t.username)||"",profileId:me(t.profileId),state:r,error:me(t.error),generation:Vh(t.generation),disconnectedAt:be(t.disconnectedAt),closeReason:me(t.closeReason),reconnecting:t.reconnecting===!0,cols:be(t.cols)??80,rows:be(t.rows)??24,createdAt:be(t.createdAt)??0,updatedAt:be(t.updatedAt)??0,lastActivityAt:be(t.lastActivityAt)??0,bytesIn:be(t.bytesIn)??0,bytesOut:be(t.bytesOut)??0,permission:Qr(t.permission)}}function Vh(e){let t=be(e);return t===void 0||t<0?0:Math.trunc(t)}function sa(e,t){let i={id:String(e||"")};return typeof t=="string"&&t.trim()!==""&&(i.reason=t.trim()),ge("sessions.disconnect",i)}function en(e,t={}){let i={id:String(e||"")},s=Xe(t)||{},r=be(s.cols),n=be(s.rows);return r!==void 0&&r>0&&(i.cols=Math.trunc(r)),n!==void 0&&n>0&&(i.rows=Math.trunc(n)),i}function ra(e,t){return ge("sessions.reconnect",en(e,t))}function jh(e){let t=Xe(e);if(!t)return null;let i=me(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh",r=t.authType==="password"||t.authType==="privateKey"||t.authType==="agent"||t.authType==="none"?t.authType:"none";return{id:i,name:me(t.name)||i,transport:s,host:me(t.host)||"",port:be(t.port)??(s==="telnet"?23:22),username:me(t.username)||"",authType:r,hasPassword:t.hasPassword===!0,hasPrivateKey:t.hasPrivateKey===!0,hasPassphrase:t.hasPassphrase===!0,folder:me(t.folder)||"",order:be(t.order)??0,createdAt:be(t.createdAt)??0,updatedAt:be(t.updatedAt)??0}}function Xs(){return ge("profiles.list",{})}function tn(e){return ge("profiles.save",{profile:e})}function na(e,t){return ge("profiles.rename",{id:String(e||""),name:String(t||"")})}function oa(e,t){return ge("profiles.setFolder",{id:String(e||""),folder:typeof t=="string"?t:""})}function aa(e){return ge("profiles.delete",{id:String(e||"")})}function Js(e){let t=Xe(e)||{},i=Array.isArray(t.profiles)?t.profiles.map(jh).filter(Boolean):[],s=new Map;for(let n of i){let o=sn(n);o!==""&&s.set(o,(s.get(o)||0)+1)}if(Array.isArray(t.folders))for(let n of t.folders){let o=Xe(n);if(!o)continue;let l=me(o.name);if(!l)continue;let c=be(o.count);s.has(l)||s.set(l,c??0)}let r=[...s.entries()].map(([n,o])=>({name:n,count:o})).sort((n,o)=>n.name.localeCompare(o.name));return{profiles:i,folders:r}}function sn(e){return e&&typeof e.folder=="string"?e.folder.trim():""}function la(e,t={}){let i=Array.isArray(e)?e:[],s=Array.isArray(t.extraFolders)?t.extraFolders:[],r=new Map;for(let c of s)typeof c=="string"&&c.trim()!==""&&r.set(c.trim(),[]);for(let c of i){let a=sn(c);r.has(a)||r.set(a,[]),r.get(a).push(c)}let n=[...r.keys()].filter(c=>c!=="");n.sort((c,a)=>c.localeCompare(a));let o=[];for(let c of n){let a=r.get(c)||[];a.length===0&&t.keepEmpty!==!0||o.push({folder:c,items:a,count:a.length})}let l=r.get("")||[];return l.length>0&&o.push({folder:"",items:l,count:l.length}),o}function ca(e={}){let t=e.transport==="telnet"?"telnet":"ssh",i={name:typeof e.name=="string"?e.name.trim():"",transport:t,host:typeof e.host=="string"?e.host.trim():"",port:be(e.port)??(t==="telnet"?23:22),username:typeof e.username=="string"?e.username.trim():"",authType:t==="ssh"?e.authType==="privateKey"||e.authType==="agent"||e.authType==="none"?e.authType:"password":"none",folder:sn(e)},s=me(e.id);s&&(i.id=s);let r=be(e.order);return r!==void 0&&(i.order=r),typeof e.password=="string"&&e.password!==""&&(i.password=e.password),typeof e.privateKey=="string"&&e.privateKey.trim()!==""&&(i.privateKey=e.privateKey),typeof e.passphrase=="string"&&e.passphrase!==""&&(i.passphrase=e.passphrase),i}function rn(e){let t=Xe(e);if(!t)return null;let i=t.action==="read"||t.action==="write"||t.action==="deny"||t.action==="lock"?t.action:"read";return{at:be(t.at)??Date.now(),sessionId:me(t.sessionId),source:t.source==="ai"?"ai":"human",action:i,detail:me(t.detail)||"",byteLength:be(t.byteLength)??0}}function Ei(e){let t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;return t<1024?String(t):t<1024*1024?`${(t/1024).toFixed(1)}K`:`${(t/(1024*1024)).toFixed(1)}M`}function zi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function os(e){return typeof e=="string"&&e!==""?e:void 0}function ha(e,t={}){let i={id:e,changedOnly:t.changedOnly===!0},s=zi(t.maxLines);return s!==void 0&&(i.maxLines=s),ge("read.screen",i)}function Zs(e={}){let t={},i=zi(e.limit);i!==void 0&&(t.limit=i);let s=zi(e.since);s!==void 0&&(t.since=s);let r=zi(e.until);r!==void 0&&(t.until=r);let n=zi(e.offset);n!==void 0&&(t.offset=n);let o=os(e.snapshot);return o!==void 0&&(t.snapshot=o),ge("history.sessions",t)}function da(e={}){return ge("history.export",e)}function nn(e={}){return ge("history.legacy.sessions",e)}function ua(e={}){return ge("history.legacy.query",e)}function fa(e={}){return ge("history.legacy.export",e)}function pa(){return ge("autolog.get",{})}function on(e={}){return ge("autolog.set",e)}function _a(e={}){let t={},i=os(e.sessionId);i!==void 0&&(t.sessionId=i);for(let n of["since","until","context","maxMatches","maxBytes","limit"]){let o=zi(e[n]);o!==void 0&&(t[n]=o)}let s=os(e.historyId);s!==void 0&&(t.historyId=s);let r=os(e.search);return r!==void 0&&(t.search=r),ge("history.query",t)}function Qs(){return ge("scripts.list",{})}function er(e){return ge("scripts.get",{name:String(e||"")})}function tr(e){return ge("scripts.save",{script:e})}function ma(e){return ge("scripts.delete",{name:e})}function ir(e={}){let t={name:String(e.name||"")},i=Xe(e.params);i&&(t.params=i);let s=Array.isArray(e.targets)?e.targets.filter(r=>typeof r=="string"&&r!==""):[];if(s.length>0)t.targets=s;else{let r=os(e.sessionId);r!==void 0&&(t.sessionId=r)}return ge("scripts.run",t)}function ki(e){let t=Xe(e);if(!t)return null;let i=me(t.id);if(!i)return null;let s=t.transport==="telnet"?"telnet":"ssh";return{id:i,title:me(t.title)||i,transport:s,host:me(t.host)||"",port:be(t.port)??(s==="telnet"?23:22),username:me(t.username)||"",createdAt:be(t.createdAt)??0,closedAt:be(t.closedAt),bytes:be(t.bytes)??0,lastTs:be(t.lastTs)??0,historyId:me(t.historyId)}}function Yh(e){let t=Xe(e);if(!t)return null;let i=s=>Array.isArray(s)?s.filter(r=>typeof r=="string"):[];return{at:be(t.at)??0,line:typeof t.line=="string"?t.line:"",before:i(t.before),after:i(t.after)}}function ga(e){let t=Xe(e)||{},i=Array.isArray(t.matches)?t.matches.map(Yh).filter(Boolean):[];return i.sort((s,r)=>s.at-r.at),{matches:i,text:typeof t.text=="string"?t.text:"",truncated:t.truncated===!0,scannedBytes:be(t.scannedBytes)??0,entry:ki(t.entry),sessions:Array.isArray(t.sessions)?t.sessions.map(ki).filter(Boolean):void 0}}function va(e){let t={};if(Array.isArray(e)){for(let s of e)if(typeof s=="string"&&s!=="")t[s]={};else if(s&&typeof s=="object"){let r=me(s.name);r&&(t[r]={},typeof s.default=="string"&&(t[r].default=s.default),typeof s.description=="string"&&(t[r].description=s.description))}return t}let i=Xe(e);if(!i)return t;for(let[s,r]of Object.entries(i))if(s)if(typeof r=="string")t[s]={default:r};else if(Xe(r)){let n={};typeof r.default=="string"&&(n.default=r.default),typeof r.description=="string"&&(n.description=r.description),t[s]=n}else t[s]={};return t}function $i(e){let t=Xe(e);if(!t)return null;let i=me(t.name);if(!i)return null;let s=va(t.params),r=typeof t.params=="number"?be(t.params):void 0,n=be(t.stepCount)??(Array.isArray(t.steps)?t.steps.length:0);return{name:i,description:me(t.description)||"",folder:me(t.folder)||"",params:s,paramCount:r??Object.keys(s).length,stepCount:n,updatedAt:be(t.updatedAt)??0}}function sr(e){let t=Xe(e);if(!t)return null;let i=me(t.name);return i?{name:i,description:typeof t.description=="string"?t.description:"",folder:typeof t.folder=="string"?t.folder:"",params:va(t.params),steps:Array.isArray(t.steps)?t.steps:[]}:null}function Gh(e){let t=Xe(e);if(!t)return null;let i=Array.isArray(t.steps)?t.steps.map(s=>{let r=Xe(s)||{};return{index:be(r.index)??0,depth:Math.max(0,be(r.depth)??0),path:me(r.path)||"",kind:me(r.kind)||"",ok:r.ok===!0,matched:r.matched===!0,text:me(r.text),cursor:me(r.cursor),error:me(r.error)}}):[];return{sessionId:me(t.sessionId)||"",ok:t.ok===!0,steps:i,stoppedAt:be(t.stoppedAt)}}function ya(e){let t=Xe(e)||{},i=Array.isArray(t.runs)?t.runs.map(Gh).filter(Boolean):[];return{ok:t.ok===!0,timedOut:t.timedOut===!0,label:me(t.label),runs:i}}function Sa(e){let t=Xe(e);if(!t||t.type!=="batch")return null;let i=me(t.batchId);return i?{batchId:i,label:me(t.label),state:t.state==="done"?"done":"step",sessionId:me(t.sessionId)||"",stepIndex:be(t.stepIndex)??0,depth:Math.max(0,be(t.depth)??0),path:me(t.path)||"",kind:me(t.kind)||"",ok:t.ok===!0,text:typeof t.text=="string"?t.text:void 0,error:me(t.error),code:me(t.code)}:null}function ba(e){let t=Xe(e)||{};return{text:typeof t.text=="string"?t.text:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(i=>typeof i=="string"):[],cursor:me(t.cursor)||"",atPrompt:t.atPrompt===!0,unchanged:t.unchanged===!0}}var Xh=/^(\d{1,9})\s*(s|m|h|d)$/i;function an(e,t=Date.now()){let i=typeof e=="string"?e.trim():"";if(i==="")return{ok:!0,at:void 0};let s=Xh.exec(i);if(s){let n=Number(s[1]),o=s[2].toLowerCase(),l=o==="s"?1e3:o==="m"?6e4:o==="h"?36e5:864e5;return Number.isFinite(n)?{ok:!0,at:t-n*l}:{ok:!1}}if(/^\d{10,16}$/.test(i)){let n=Number(i);return Number.isFinite(n)?{ok:!0,at:i.length===10?n*1e3:n}:{ok:!1}}let r=Date.parse(i);return Number.isFinite(r)?{ok:!0,at:r}:{ok:!1}}function Qt(e,t=2){return String(e).padStart(t,"0")}function ln(e){let t=typeof e=="number"&&Number.isFinite(e)?e:0,i=new Date(t);return Number.isNaN(i.getTime())?"--:--:--.---":`${Qt(i.getHours())}:${Qt(i.getMinutes())}:${Qt(i.getSeconds())}.${Qt(i.getMilliseconds(),3)}`}function cn(e,t=Date.now()){let i=typeof e=="number"&&Number.isFinite(e)?e:0,s=new Date(i);if(Number.isNaN(s.getTime()))return"—";let r=new Date(t),n=s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate(),o=`${Qt(s.getHours())}:${Qt(s.getMinutes())}:${Qt(s.getSeconds())}`;return n?o:`${Qt(s.getMonth()+1)}-${Qt(s.getDate())} ${o.slice(0,5)}`}function hn(e){return String(e??"").replace(/\s+/gu," ").trim()}function dn(e,t){let i=un(e),s=typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):200;return i.length>s?`${i.slice(0,Math.max(0,s-1))}…`:i}function un(e){if(typeof e=="string")return e;if(e==null)return"";try{return String(e)}catch{return""}}function wa(e){let t=typeof e=="string"?e.trim():"";if(t==="")return null;try{return new RegExp(t,"gi")}catch{try{return new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi")}catch{return null}}}function Ca(e){let t=typeof e=="string"?e.trim():"";if(t!=="")try{return new RegExp(t),t}catch{return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}function xa(e,t){let i=un(e);if(!t)return[{text:i,hit:!1}];let s;try{s=new RegExp(t.source,t.flags.includes("g")?t.flags:`${t.flags}g`)}catch{return[{text:i,hit:!1}]}let r=[],n=0,o=0,l=null;for(;(l=s.exec(i))!==null&&(o+=1,!(o>1e3));){if(l[0]===""){if(s.lastIndex+=1,s.lastIndex>i.length&&n>=i.length)break;continue}l.index>n&&r.push({text:i.slice(n,l.index),hit:!1}),r.push({text:l[0],hit:!0}),n=l.index+l[0].length}return n<i.length&&r.push({text:i.slice(n),hit:!1}),r.length>0?r:[{text:i,hit:!1}]}async function rr(e,t){let i=un(e);if(i==="")return!1;try{if(typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(i),!0}catch{}if(!t||typeof document>"u"||typeof document.createElement!="function")return!1;let s=null;try{s=document.createElement("textarea"),s.value=i,s.setAttribute("readonly","readonly"),s.style.position="absolute",s.style.left="-9999px",s.style.top="0",s.style.opacity="0",t.appendChild(s),s.focus(),s.select();let r=typeof document.execCommand=="function"?document.execCommand("copy")===!0:!1;return t.removeChild(s),r}catch{try{s&&s.parentNode&&s.parentNode.removeChild(s)}catch{}return!1}}var Ra=require("react");var Jh=500;function Ui(){return{batchId:null,label:null,state:"idle",startedAt:0,lines:[],runs:null,error:null,pending:!1}}var hs=Object.freeze({kind:"terminal"}),Zh=["history","scripts","profiles"],Qh={sessions:[],selectedId:null,view:"terminal",resets:{},connectDraft:null,viewStack:[hs],panel:null,highlightProfileId:null,ready:!1,transportError:null,toast:null,audit:{},owner:void 0,batch:Ui()},de=Qh,fn=new Set,ci=0,nr=new Map,ka=0;function pn(e,t,i){let s=nr.get(e.id);nr.set(e.id,e.generation);let r=de.resets[e.id],n=s!==void 0&&e.generation>s;return!i&&!n||r&&e.generation<=r.generation?null:(ka+=1,{seq:ka,generation:e.generation,reason:typeof t=="string"&&t?t:null,at:Date.now()})}function La(e,t){let i=e.findIndex(s=>s.id===t.id);return i>=0?(e[i]=t,e):(e.push(t),e)}function Ta(e,t,i){return t?{...i,resets:{...de.resets,[e.id]:t}}:i}function or(){return de}function ed(e){return fn.add(e),()=>{fn.delete(e)}}function nt(e){let t=typeof e=="function"?e(de):e;de={...de,...t};for(let i of[...fn])try{i()}catch(s){console.error("[aiterm] state listener failed",s)}}function zt(){return(0,Ra.useSyncExternalStore)(ed,or,or)}function Da(e){let t=Array.isArray(e)?e.map(li).filter(Boolean):[],i=new Set(t.map(n=>n.id)),s={};for(let n of Object.keys(de.resets))i.has(n)&&(s[n]=de.resets[n]);for(let n of t){let o=pn(n,void 0,!1);o&&(s[n.id]=o)}for(let n of[...nr.keys()])i.has(n)||nr.delete(n);let r=de.selectedId&&t.some(n=>n.id===de.selectedId)?de.selectedId:t.length>0?t[0].id:null;nt({sessions:t,selectedId:r,ready:!0,transportError:null,resets:s})}function $t(e){let t=li(e);if(!t)return null;let i=pn(t,void 0,!1),s=La(de.sessions.slice(),t),r=de.selectedId??t.id;return nt(Ta(t,i,{sessions:s,selectedId:r,ready:!0})),t}function _n(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},i=li(t.session);if(!i)return null;let s=pn(i,t.reason,!0),r=La(de.sessions.slice(),i),n=de.selectedId??i.id;return nt(Ta(i,s,{sessions:r,selectedId:n,ready:!0})),s}function Aa(e){return de.resets[e]||null}var Ba=new Map;function mn(e,t,i){if(!e)return;let s=Number(t),r=Number(i);!Number.isFinite(s)||!Number.isFinite(r)||s<1||r<1||Ba.set(String(e),{cols:Math.trunc(s),rows:Math.trunc(r)})}function Ma(e){return Ba.get(String(e||""))||null}function ds(e,t){if(!t)return;let i=Qr(t),s=de.sessions.map(r=>r.id===e?{...r,permission:i}:r);nt({sessions:s})}function qi(e,t){let i=de.sessions.map(s=>s.id===e?{...s,state:"closed",error:t||s.error}:s);nt({sessions:i})}function Pa(e,t={}){let i=e.length>0?e:[hs],s=i[i.length-1];return{viewStack:i,view:s.kind==="connect"?"connect":"terminal",panel:s.kind==="panel"?s.name:null,connectDraft:s.kind==="connect"&&s.draft||null,...t}}function ar(e,t={}){nt(Pa(e,t))}function ls(){return de.viewStack[de.viewStack.length-1]||hs}function Ia(){return de.viewStack.length>1}function gn(){if(de.viewStack.length<=1)return null;let e=ls();return ar(de.viewStack.slice(0,-1)),e}function Ri(e){nt(Pa([hs],{selectedId:e,highlightProfileId:null}))}function Vi(e){let t=e&&typeof e=="object"&&typeof e.id=="string"&&e.id?e:null,i=de.viewStack.slice(),s=i[i.length-1],r=s.kind==="connect"&&s.draft&&s.draft.id?s.draft.id:null,n=t?t.id:null;s.kind==="connect"&&r===n||(s.kind==="connect"&&i.pop(),i.push({kind:"connect",draft:t}),ar(i,{highlightProfileId:null}))}function vn(e){if(ls().kind!=="connect")return null;let t=de.viewStack.slice(0,-1),i=typeof e=="string"&&e?e:de.highlightProfileId;return ar(t,{highlightProfileId:i||null}),ls()}function lr(e){if(e==null||!Zh.includes(e)){Li();return}if(!de.selectedId&&e==="profiles")return;let t=ls();if(t.kind==="panel"&&t.name===e)return;let i=de.viewStack.slice();i[i.length-1].kind!=="terminal"&&i.pop(),i.push({kind:"panel",name:e,sessionId:de.selectedId}),ar(i)}function Li(){return ls().kind!=="panel"?null:gn()}function Oa(e){let t=typeof e=="string"&&e?e:null;de.highlightProfileId!==t&&nt({highlightProfileId:t})}function Na(e){nt({batch:{...Ui(),label:typeof e=="string"&&e?e:null,state:"running",startedAt:Date.now(),pending:!0}})}function yn(e={}){let t=de.batch,i=e.result===void 0||e.result===null?t.runs:ya(e.result),s=typeof e.error=="string"&&e.error?e.error:null;nt({batch:{...t,state:"done",pending:!1,runs:i,error:s}})}function td(e){let t=Sa(e);if(!t)return;let i=de.batch;if(t.state==="done"){if(i.batchId&&i.batchId!==t.batchId)return;nt({batch:{...i,batchId:i.batchId||t.batchId,label:i.label||t.label||null,state:"done",pending:!1}});return}let s=i,r=i.batchId!==null&&i.batchId!==t.batchId;i.state!=="running"||r?s={...Ui(),batchId:t.batchId,label:t.label||null,state:"running",startedAt:Date.now()}:i.batchId||(s={...i,batchId:t.batchId,label:i.label||t.label||null});let n={key:`${t.batchId}:${t.sessionId}:${t.stepIndex}:${s.lines.length}`,batchId:t.batchId,sessionId:t.sessionId,stepIndex:t.stepIndex,depth:t.depth,path:t.path,kind:t.kind,ok:t.ok,text:t.text,error:t.error,code:t.code,at:Date.now()};nt({batch:{...s,lines:s.lines.concat(n).slice(-Jh)}})}function J(e){e&&(nt({toast:{text:e,id:Date.now()+Math.random()}}),ci&&clearTimeout(ci),ci=setTimeout(()=>{ci=0,nt({toast:null})},3500),typeof ci=="object"&&ci&&typeof ci.unref=="function"&&ci.unref())}function Ea(e){de.transportError!==(e||null)&&nt({transportError:e||null})}function Fa(e,t){if(!e)return;let i=Array.isArray(t)?t.map(rn).filter(Boolean):[];nt({audit:{...de.audit,[e]:i.slice(-200)}})}function Ha(e,t){let i=rn(t);if(!i||i.sessionId&&i.sessionId!==e)return;let r=(de.audit[e]||[]).concat({...i,sessionId:i.sessionId||e});nt({audit:{...de.audit,[e]:r.slice(-200)}})}function cr(e){let t=typeof e=="string"&&e.length>0?e:void 0;if(t===de.owner)return;let i=Ki>0;if(i&&hi){try{hi.close()}catch{}hi=null}nt({owner:t,sessions:[],selectedId:null,ready:!1,viewStack:[hs],panel:null,batch:Ui(),connectDraft:null,highlightProfileId:null}),i&&(Ki-=1,Sn()),cs().catch(()=>{})}async function cs(){let e=await ge("sessions.list",{});return Da(e?e.sessions:[]),de.sessions}ia(()=>de.owner);var hi=null,Ki=0;function Sn(){if(Ki+=1,hi||typeof EventSource>"u")return;let e;try{let t=de.owner,i=typeof t=="string"&&t.length>0?`?owner=${encodeURIComponent(t)}`:"";e=new EventSource(as+"/events"+i)}catch{return}hi=e,e.onmessage=t=>{let i=Gs(t.data);if(i){if(i.type==="sessions")Da(i.sessions);else if(i.type==="state")$t(i.session);else if(i.type==="reset")try{_n(i)}catch(s){console.error("[aiterm] reset frame failed",s)}else if(i.type==="batch")try{td(i)}catch(s){console.error("[aiterm] batch frame failed",s)}}},e.onopen=()=>{Ea(null),de.ready||cs().catch(()=>{})},e.onerror=()=>{Ea("stream"),de.ready||cs().catch(()=>{})}}function Wa(){if(Ki=Math.max(0,Ki-1),!(Ki>0||!hi)){try{hi.close()}catch{}hi=null}}var Ct=require("react");/**
|
|
12
12
|
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
|
|
13
13
|
* @license MIT
|
|
14
14
|
*
|
|
@@ -19,20 +19,20 @@ var Ar=Object.defineProperty;var Ic=Object.getOwnPropertyDescriptor;var Oc=Objec
|
|
|
19
19
|
* Fabrice Bellard's javascript vt100 for jslinux:
|
|
20
20
|
* http://bellard.org/jslinux/
|
|
21
21
|
* Copyright (c) 2011 Fabrice Bellard
|
|
22
|
-
*/var
|
|
22
|
+
*/var jl=Object.defineProperty,id=Object.getOwnPropertyDescriptor,sd=(e,t)=>{for(var i in t)jl(e,i,{get:t[i],enumerable:!0})},ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?id(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(s?o(t,i,r):o(r))||r);return s&&r&&jl(t,i,r),r},U=(e,t)=>(i,s)=>t(i,s,e),za="Terminal input",Nn={get:()=>za,set:e=>za=e},$a="Too much output to announce, navigate to rows manually to read",Fn={get:()=>$a,set:e=>$a=e};function rd(e){return e.replace(/\r?\n/g,"\r")}function nd(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function od(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function ad(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");Yl(r,t,i,s)}}function Yl(e,t,i,s){e=rd(e),e=nd(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Gl(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Ka(e,t,i,s,r){Gl(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function _i(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Br(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let n=e[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var ld=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[s++]=(this._interim-55296)*1024+n-56320+65536:(t[s++]=this._interim,t[s++]=n),this._interim=0}for(let n=r;n<i;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=i)return this._interim=o,s;let l=e.charCodeAt(n);56320<=l&&l<=57343?t[s++]=(o-55296)*1024+l-56320+65536:(t[s++]=o,t[s++]=l);continue}o!==65279&&(t[s++]=o)}return s}},cd=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r,n,o,l,c=0,a=0;if(this.interim[0]){let _=!1,m=this.interim[0];m&=(m&224)===192?31:(m&240)===224?15:7;let p=0,g;for(;(g=this.interim[++p]&63)&&p<4;)m<<=6,m|=g;let y=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,x=y-p;for(;a<x;){if(a>=i)return 0;if(g=e[a++],(g&192)!==128){a--,_=!0;break}else this.interim[p++]=g,m<<=6,m|=g&63}_||(y===2?m<128?a--:t[s++]=m:y===3?m<2048||m>=55296&&m<=57343||m===65279||(t[s++]=m):m<65536||m>1114111||(t[s++]=m)),this.interim.fill(0)}let u=i-4,d=a;for(;d<i;){for(;d<u&&!((r=e[d])&128)&&!((n=e[d+1])&128)&&!((o=e[d+2])&128)&&!((l=e[d+3])&128);)t[s++]=r,t[s++]=n,t[s++]=o,t[s++]=l,d+=4;if(r=e[d++],r<128)t[s++]=r;else if((r&224)===192){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(c=(r&31)<<6|n&63,c<128){d--;continue}t[s++]=c}else if((r&240)===224){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[d++],(o&192)!==128){d--;continue}if(c=(r&15)<<12|(n&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[s++]=c}else if((r&248)===240){if(d>=i)return this.interim[0]=r,s;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,s;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(r&7)<<18|(n&63)<<12|(o&63)<<6|l&63,c<65536||c>1114111)continue;t[s++]=c}}return s}},Xl="",mi=" ",Ms=class Jl{constructor(){this.fg=0,this.bg=0,this.extended=new Cr}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Jl;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Cr=class Zl{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Zl(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Nt=class Ql extends Ms{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Cr,this.combinedData=""}static fromCharData(t){let i=new Ql;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?_i(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(s-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Ua="di$target",Hn="di$dependencies",bn=new Map;function hd(e){return e[Hn]||[]}function dt(e){if(bn.has(e))return bn.get(e);let t=function(i,s,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");dd(t,i,r)};return t._id=e,bn.set(e,t),t}function dd(e,t,i){t[Ua]===t?t[Hn].push({id:e,index:i}):(t[Hn]=[{id:e,index:i}],t[Ua]=t)}var St=dt("BufferService"),ec=dt("CoreMouseService"),Oi=dt("CoreService"),ud=dt("CharsetService"),Eo=dt("InstantiationService"),tc=dt("LogService"),bt=dt("OptionsService"),ic=dt("OscLinkService"),fd=dt("UnicodeService"),Ps=dt("DecorationService"),Wn=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],r=this._optionsService.rawOptions.linkHandler,n=new Nt,o=i.getTrimmedLength(),l=-1,c=-1,a=!1;for(let u=0;u<o;u++)if(!(c===-1&&!i.hasContent(u))){if(i.loadCell(u,n),n.hasExtendedAttrs()&&n.extended.urlId)if(c===-1){c=u,l=n.extended.urlId;continue}else a=n.extended.urlId!==l;else c!==-1&&(a=!0);if(a||c!==-1&&u===o-1){let d=this._oscLinkService.getLinkData(l)?.uri;if(d){let _={start:{x:c+1,y:e},end:{x:u+(!a&&u===o-1?1:0),y:e}},m=!1;if(!r?.allowNonHttpProtocols)try{let p=new URL(d);["http:","https:"].includes(p.protocol)||(m=!0)}catch{m=!0}m||s.push({text:d,range:_,activate:(p,g)=>r?r.activate(p,g,_):pd(p,g),hover:(p,g)=>r?.hover?.(p,g,_),leave:(p,g)=>r?.leave?.(p,g,_)})}a=!1,n.hasExtendedAttrs()&&n.extended.urlId?(c=u,l=n.extended.urlId):(c=-1,l=-1)}}t(s)}};Wn=ze([U(0,St),U(1,bt),U(2,ic)],Wn);function pd(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
23
23
|
|
|
24
|
-
WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var
|
|
24
|
+
WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Mr=dt("CharSizeService"),ri=dt("CoreBrowserService"),Ro=dt("MouseService"),ni=dt("RenderService"),_d=dt("SelectionService"),sc=dt("CharacterJoinerService"),Xi=dt("ThemeService"),rc=dt("LinkProviderService"),md=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?qa.isErrorNoTelemetry(e)?new qa(e.message+`
|
|
25
25
|
|
|
26
26
|
`+e.stack):new Error(e.message+`
|
|
27
27
|
|
|
28
|
-
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},
|
|
29
|
-
`).map(d=>d.trim().replace("at ","")).filter(d=>d!=="");return a(u,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),u.reverse()}let n=new
|
|
30
|
-
`),
|
|
31
|
-
`)).size}/${s.length} leaks) at ${
|
|
32
|
-
`)),
|
|
28
|
+
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},gd=new md;function _r(e){vd(e)||gd.onUnexpectedError(e)}var zn="Canceled";function vd(e){return e instanceof yd?!0:e instanceof Error&&e.name===zn&&e.message===zn}var yd=class extends Error{constructor(){super(zn),this.name=this.message}};function Sd(e){return e?new Error(`Illegal argument: ${e}`):new Error("Illegal argument")}var qa=class $n extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $n)return t;let i=new $n;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Kn=class nc extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,nc.prototype)}};function bd(e,t,i=0,s=e.length){let r=i,n=s;for(;r<n;){let o=Math.floor((r+n)/2);t(e[o])?r=o+1:n=o}return r-1}var wd=class oc{constructor(t){this._array=t,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(oc.assertInvariants){if(this._prevFindLastPredicate){for(let s of this._array)if(this._prevFindLastPredicate(s)&&!t(s))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=t}let i=bd(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=i+1,i===-1?void 0:this._array[i]}};wd.assertInvariants=!1;function Lt(e,t=0){return e[e.length-(1+t)]}var Un;(e=>{function t(n){return n<0}e.isLessThan=t;function i(n){return n<=0}e.isLessThanOrEqual=i;function s(n){return n>0}e.isGreaterThan=s;function r(n){return n===0}e.isNeitherLessOrGreaterThan=r,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Un||(Un={}));function Cd(e,t){return(i,s)=>t(e(i),e(s))}var xd=(e,t)=>e-t,Va=class qn{constructor(t){this.iterate=t}forEach(t){this.iterate(i=>(t(i),!0))}toArray(){let t=[];return this.iterate(i=>(t.push(i),!0)),t}filter(t){return new qn(i=>this.iterate(s=>t(s)?i(s):!0))}map(t){return new qn(i=>this.iterate(s=>i(t(s))))}some(t){let i=!1;return this.iterate(s=>(i=t(s),!i)),i}findFirst(t){let i;return this.iterate(s=>t(s)?(i=s,!1):!0),i}findLast(t){let i;return this.iterate(s=>(t(s)&&(i=s),!0)),i}findLastMaxBy(t){let i,s=!0;return this.iterate(r=>((s||Un.isGreaterThan(t(r,i)))&&(s=!1,i=r),!0)),i}};Va.empty=new Va(e=>{});function kd(e,t){let i=Object.create(null);for(let s of e){let r=t(s),n=i[r];n||(n=i[r]=[]),n.push(s)}return i}var ja,Ya,N_=class{constructor(e,t){this.toKey=t,this._map=new Map,this[ja]="SetWithKey";for(let i of e)this.add(i)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach(i=>e.call(t,i,i,this))}[(Ya=Symbol.iterator,ja=Symbol.toStringTag,Ya)](){return this.values()}},Ed=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){let i=this.map.get(e);i&&(i.delete(t),i.size===0&&this.map.delete(e))}forEach(e,t){let i=this.map.get(e);i&&i.forEach(t)}get(e){return this.map.get(e)||new Set}};function Rd(e,t){let i=this,s=!1,r;return function(){if(s)return r;if(s=!0,t)try{r=e.apply(i,arguments)}finally{t()}else r=e.apply(i,arguments);return r}}var Vn;(e=>{function t(k){return k&&typeof k=="object"&&typeof k[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*r(k){yield k}e.single=r;function n(k){return t(k)?k:r(k)}e.wrap=n;function o(k){return k||i}e.from=o;function*l(k){for(let M=k.length-1;M>=0;M--)yield k[M]}e.reverse=l;function c(k){return!k||k[Symbol.iterator]().next().done===!0}e.isEmpty=c;function a(k){return k[Symbol.iterator]().next().value}e.first=a;function u(k,M){let Z=0;for(let K of k)if(M(K,Z++))return!0;return!1}e.some=u;function d(k,M){for(let Z of k)if(M(Z))return Z}e.find=d;function*_(k,M){for(let Z of k)M(Z)&&(yield Z)}e.filter=_;function*m(k,M){let Z=0;for(let K of k)yield M(K,Z++)}e.map=m;function*p(k,M){let Z=0;for(let K of k)yield*M(K,Z++)}e.flatMap=p;function*g(...k){for(let M of k)yield*M}e.concat=g;function y(k,M,Z){let K=Z;for(let ye of k)K=M(K,ye);return K}e.reduce=y;function*x(k,M,Z=k.length){for(M<0&&(M+=k.length),Z<0?Z+=k.length:Z>k.length&&(Z=k.length);M<Z;M++)yield k[M]}e.slice=x;function q(k,M=Number.POSITIVE_INFINITY){let Z=[];if(M===0)return[Z,k];let K=k[Symbol.iterator]();for(let ye=0;ye<M;ye++){let ce=K.next();if(ce.done)return[Z,e.empty()];Z.push(ce.value)}return[Z,{[Symbol.iterator](){return K}}]}e.consume=q;async function W(k){let M=[];for await(let Z of k)M.push(Z);return Promise.resolve(M)}e.asyncToArray=W})(Vn||(Vn={}));var Ld=!1,Mi=null,Td=class ac{constructor(){this.livingDisposables=new Map}getDisposableData(t){let i=this.livingDisposables.get(t);return i||(i={parent:null,source:null,isSingleton:!1,value:t,idx:ac.idx++},this.livingDisposables.set(t,i)),i}trackDisposable(t){let i=this.getDisposableData(t);i.source||(i.source=new Error().stack)}setParent(t,i){let s=this.getDisposableData(t);s.parent=i}markAsDisposed(t){this.livingDisposables.delete(t)}markAsSingleton(t){this.getDisposableData(t).isSingleton=!0}getRootParent(t,i){let s=i.get(t);if(s)return s;let r=t.parent?this.getRootParent(this.getDisposableData(t.parent),i):t;return i.set(t,r),r}getTrackedDisposables(){let t=new Map;return[...this.livingDisposables.entries()].filter(([,i])=>i.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,i){let s;if(i)s=i;else{let c=new Map,a=[...this.livingDisposables.values()].filter(d=>d.source!==null&&!this.getRootParent(d,c).isSingleton);if(a.length===0)return;let u=new Set(a.map(d=>d.value));if(s=a.filter(d=>!(d.parent&&u.has(d.parent))),s.length===0)throw new Error("There are cyclic diposable chains!")}if(!s)return;function r(c){function a(d,_){for(;d.length>0&&_.some(m=>typeof m=="string"?m===d[0]:d[0].match(m));)d.shift()}let u=c.source.split(`
|
|
29
|
+
`).map(d=>d.trim().replace("at ","")).filter(d=>d!=="");return a(u,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),u.reverse()}let n=new Ed;for(let c of s){let a=r(c);for(let u=0;u<=a.length;u++)n.add(a.slice(0,u).join(`
|
|
30
|
+
`),c)}s.sort(Cd(c=>c.idx,xd));let o="",l=0;for(let c of s.slice(0,t)){l++;let a=r(c),u=[];for(let d=0;d<a.length;d++){let _=a[d];_=`(shared with ${n.get(a.slice(0,d+1).join(`
|
|
31
|
+
`)).size}/${s.length} leaks) at ${_}`;let m=n.get(a.slice(0,d).join(`
|
|
32
|
+
`)),p=kd([...m].map(g=>r(g)[d]),g=>g);delete p[a[d]];for(let[g,y]of Object.entries(p))u.unshift(` - stacktraces of ${y.length} other leaks continue with ${g}`);u.unshift(_)}o+=`
|
|
33
33
|
|
|
34
34
|
|
|
35
|
-
==================== Leaking disposable ${l}/${s.length}: ${
|
|
35
|
+
==================== Leaking disposable ${l}/${s.length}: ${c.value.constructor.name} ====================
|
|
36
36
|
${u.join(`
|
|
37
37
|
`)}
|
|
38
38
|
============================================================
|
|
@@ -42,19 +42,19 @@ ${u.join(`
|
|
|
42
42
|
|
|
43
43
|
... and ${s.length-t} more leaking disposables
|
|
44
44
|
|
|
45
|
-
`),{leaks:s,details:o}}};Ed.idx=0;function Rd(e){_i=e}if(kd){let e="__is_disposable_tracked__";Rd(new class{trackDisposable(t){let i=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[e]||console.log(i)},3e3)}setParent(t,i){if(t&&t!==he.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==he.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}function pr(e){return _i?.trackDisposable(e),e}function _r(e){_i?.markAsDisposed(e)}function cs(e,t){_i?.setParent(e,t)}function Td(e,t){if(_i)for(let i of e)_i.setParent(i,t)}function Pa(e){return _i?.markAsSingleton(e),e}function mi(e){if(En.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function Dd(...e){let t=Te(()=>mi(e));return Td(e,t),t}function Te(e){let t=pr({dispose:xd(()=>{_r(t),e()})});return t}var jl=class Yl{constructor(){this._toDispose=new Set,this._isDisposed=!1,pr(this)}dispose(){this._isDisposed||(_r(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{mi(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return cs(t,this),this._isDisposed?Yl.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),cs(t,null))}};jl.DISABLE_DISPOSED_WARNING=!1;var si=jl,he=class{constructor(){this._store=new si,pr(this),cs(this._store,this)}dispose(){_r(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};he.None=Object.freeze({dispose(){}});var Li=class{constructor(){this._isDisposed=!1,pr(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&cs(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,_r(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&cs(e,null),e}},wt=typeof window=="object"?window:globalThis,Rn=class Tn{constructor(t){this.element=t,this.next=Tn.Undefined,this.prev=Tn.Undefined}};Rn.Undefined=new Rn(void 0);var Me=Rn,Ia=class{constructor(){this._first=Me.Undefined,this._last=Me.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Me.Undefined}clear(){let e=this._first;for(;e!==Me.Undefined;){let t=e.next;e.prev=Me.Undefined,e.next=Me.Undefined,e=t}this._first=Me.Undefined,this._last=Me.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Me(e);if(this._first===Me.Undefined)this._first=i,this._last=i;else if(t){let r=this._last;this._last=i,i.prev=r,r.next=i}else{let r=this._first;this._first=i,i.next=r,r.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==Me.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Me.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Me.Undefined&&e.next!==Me.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Me.Undefined&&e.next===Me.Undefined?(this._first=Me.Undefined,this._last=Me.Undefined):e.next===Me.Undefined?(this._last=this._last.prev,this._last.next=Me.Undefined):e.prev===Me.Undefined&&(this._first=this._first.next,this._first.prev=Me.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Me.Undefined;)yield e.element,e=e.next}},Bd=globalThis.performance&&typeof globalThis.performance.now=="function",Ld=class Gl{static create(t){return new Gl(t)}constructor(t){this._now=Bd&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Ad=!1,Oa=!1,Md=!1,rt;(e=>{e.None=()=>he.None;function t(k){if(Md){let{onDidAddListener:E}=k,A=Ln.create(),L=0;k.onDidAddListener=()=>{++L===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),A.print()),E?.()}}}function i(k,E){return m(k,()=>{},0,void 0,!0,void 0,E)}e.defer=i;function s(k){return(E,A=null,L)=>{let T=!1,b;return b=k(M=>{if(!T)return b?b.dispose():T=!0,E.call(A,M)},null,L),T&&b.dispose(),b}}e.once=s;function r(k,E,A){return u((L,T=null,b)=>k(M=>L.call(T,E(M)),null,b),A)}e.map=r;function n(k,E,A){return u((L,T=null,b)=>k(M=>{E(M),L.call(T,M)},null,b),A)}e.forEach=n;function o(k,E,A){return u((L,T=null,b)=>k(M=>E(M)&&L.call(T,M),null,b),A)}e.filter=o;function l(k){return k}e.signal=l;function h(...k){return(E,A=null,L)=>{let T=Dd(...k.map(b=>b(M=>E.call(A,M))));return d(T,L)}}e.any=h;function a(k,E,A,L){let T=A;return r(k,b=>(T=E(T,b),T),L)}e.reduce=a;function u(k,E){let A,L={onWillAddFirstListener(){A=k(T.fire,T)},onDidRemoveLastListener(){A?.dispose()}};E||t(L);let T=new N(L);return E?.add(T),T.event}function d(k,E){return E instanceof Array?E.push(k):E&&E.add(k),k}function m(k,E,A=100,L=!1,T=!1,b,M){let B,te,Se,ne=0,_e,Oe={leakWarningThreshold:b,onWillAddFirstListener(){B=k(W=>{ne++,te=E(te,W),L&&!Se&&(se.fire(te),te=void 0),_e=()=>{let q=te;te=void 0,Se=void 0,(!L||ne>1)&&se.fire(q),ne=0},typeof A=="number"?(clearTimeout(Se),Se=setTimeout(_e,A)):Se===void 0&&(Se=0,queueMicrotask(_e))})},onWillRemoveListener(){T&&ne>0&&_e?.()},onDidRemoveLastListener(){_e=void 0,B.dispose()}};M||t(Oe);let se=new N(Oe);return M?.add(se),se.event}e.debounce=m;function p(k,E=0,A){return e.debounce(k,(L,T)=>L?(L.push(T),L):[T],E,void 0,!0,void 0,A)}e.accumulate=p;function _(k,E=(L,T)=>L===T,A){let L=!0,T;return o(k,b=>{let M=L||!E(b,T);return L=!1,T=b,M},A)}e.latch=_;function g(k,E,A){return[e.filter(k,E,A),e.filter(k,L=>!E(L),A)]}e.split=g;function y(k,E=!1,A=[],L){let T=A.slice(),b=k(te=>{T?T.push(te):B.fire(te)});L&&L.add(b);let M=()=>{T?.forEach(te=>B.fire(te)),T=null},B=new N({onWillAddFirstListener(){b||(b=k(te=>B.fire(te)),L&&L.add(b))},onDidAddFirstListener(){T&&(E?setTimeout(M):M())},onDidRemoveLastListener(){b&&b.dispose(),b=null}});return L&&L.add(B),B.event}e.buffer=y;function x(k,E){return(A,L,T)=>{let b=E(new z);return k(function(M){let B=b.evaluate(M);B!==j&&A.call(L,B)},void 0,T)}}e.chain=x;let j=Symbol("HaltChainable");class z{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(A=>(E(A),A)),this}filter(E){return this.steps.push(A=>E(A)?A:j),this}reduce(E,A){let L=A;return this.steps.push(T=>(L=E(L,T),L)),this}latch(E=(A,L)=>A===L){let A=!0,L;return this.steps.push(T=>{let b=A||!E(T,L);return A=!1,L=T,b?T:j}),this}evaluate(E){for(let A of this.steps)if(E=A(E),E===j)break;return E}}function C(k,E,A=L=>L){let L=(...B)=>M.fire(A(...B)),T=()=>k.on(E,L),b=()=>k.removeListener(E,L),M=new N({onWillAddFirstListener:T,onDidRemoveLastListener:b});return M.event}e.fromNodeEventEmitter=C;function O(k,E,A=L=>L){let L=(...B)=>M.fire(A(...B)),T=()=>k.addEventListener(E,L),b=()=>k.removeEventListener(E,L),M=new N({onWillAddFirstListener:T,onDidRemoveLastListener:b});return M.event}e.fromDOMEventEmitter=O;function X(k){return new Promise(E=>s(k)(E))}e.toPromise=X;function $(k){let E=new N;return k.then(A=>{E.fire(A)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=$;function ye(k,E){return k(A=>E.fire(A))}e.forward=ye;function de(k,E,A){return E(A),k(L=>E(L))}e.runAndSubscribe=de;class fe{constructor(E,A){this._observable=E,this._counter=0,this._hasChanged=!1;let L={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};A||t(L),this.emitter=new N(L),A&&A.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,A){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function Z(k,E){return new fe(k,E).emitter.event}e.fromObservable=Z;function we(k){return(E,A,L)=>{let T=0,b=!1,M={beginUpdate(){T++},endUpdate(){T--,T===0&&(k.reportChanges(),b&&(b=!1,E.call(A)))},handlePossibleChange(){},handleChange(){b=!0}};k.addObserver(M),k.reportChanges();let B={dispose(){k.removeObserver(M)}};return L instanceof si?L.add(B):Array.isArray(L)&&L.push(B),B}}e.fromObservableLight=we})(rt||(rt={}));var Dn=class Bn{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Bn._idPool++}`,Bn.all.add(this)}start(t){this._stopWatch=new Ld,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Dn.all=new Set,Dn._idPool=0;var Pd=Dn,Na=-1,Xl=class Jl{constructor(t,i,s=(Jl._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,i){let s=this.threshold;if(s<=0||i<s)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[n,o]=this.getMostFrequentStack(),l=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${o}):`;console.warn(l),console.warn(n);let h=new Od(l,n);this._errorHandler(h)}return()=>{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,r]of this._stacks)(!t||i<r)&&(t=[s,r],i=r);return t}};Xl._idPool=1;var Id=Xl,Ln=class Zl{constructor(t){this.value=t}static create(){let t=new Error;return new Zl(t.stack??"")}print(){console.warn(this.value.split(`
|
|
45
|
+
`),{leaks:s,details:o}}};Td.idx=0;function Dd(e){Mi=e}if(Ld){let e="__is_disposable_tracked__";Dd(new class{trackDisposable(t){let i=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[e]||console.log(i)},3e3)}setParent(t,i){if(t&&t!==ve.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==ve.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}function Pr(e){return Mi?.trackDisposable(e),e}function Ir(e){Mi?.markAsDisposed(e)}function Ts(e,t){Mi?.setParent(e,t)}function Ad(e,t){if(Mi)for(let i of e)Mi.setParent(i,t)}function Ga(e){return Mi?.markAsSingleton(e),e}function Pi(e){if(Vn.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function Bd(...e){let t=Be(()=>Pi(e));return Ad(e,t),t}function Be(e){let t=Pr({dispose:Rd(()=>{Ir(t),e()})});return t}var lc=class cc{constructor(){this._toDispose=new Set,this._isDisposed=!1,Pr(this)}dispose(){this._isDisposed||(Ir(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Pi(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return Ts(t,this),this._isDisposed?cc.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),Ts(t,null))}};lc.DISABLE_DISPOSED_WARNING=!1;var gi=lc,ve=class{constructor(){this._store=new gi,Pr(this),Ts(this._store,this)}dispose(){Ir(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};ve.None=Object.freeze({dispose(){}});var Gi=class{constructor(){this._isDisposed=!1,Pr(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Ts(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Ir(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Ts(e,null),e}},At=typeof window=="object"?window:globalThis,jn=class Yn{constructor(t){this.element=t,this.next=Yn.Undefined,this.prev=Yn.Undefined}};jn.Undefined=new jn(void 0);var Ne=jn,Xa=class{constructor(){this._first=Ne.Undefined,this._last=Ne.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ne.Undefined}clear(){let e=this._first;for(;e!==Ne.Undefined;){let t=e.next;e.prev=Ne.Undefined,e.next=Ne.Undefined,e=t}this._first=Ne.Undefined,this._last=Ne.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Ne(e);if(this._first===Ne.Undefined)this._first=i,this._last=i;else if(t){let r=this._last;this._last=i,i.prev=r,r.next=i}else{let r=this._first;this._first=i,i.next=r,r.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==Ne.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ne.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ne.Undefined&&e.next!==Ne.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ne.Undefined&&e.next===Ne.Undefined?(this._first=Ne.Undefined,this._last=Ne.Undefined):e.next===Ne.Undefined?(this._last=this._last.prev,this._last.next=Ne.Undefined):e.prev===Ne.Undefined&&(this._first=this._first.next,this._first.prev=Ne.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Ne.Undefined;)yield e.element,e=e.next}},Md=globalThis.performance&&typeof globalThis.performance.now=="function",Pd=class hc{static create(t){return new hc(t)}constructor(t){this._now=Md&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Id=!1,Ja=!1,Od=!1,ht;(e=>{e.None=()=>ve.None;function t(R){if(Od){let{onDidAddListener:E}=R,B=Jn.create(),A=0;R.onDidAddListener=()=>{++A===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),B.print()),E?.()}}}function i(R,E){return _(R,()=>{},0,void 0,!0,void 0,E)}e.defer=i;function s(R){return(E,B=null,A)=>{let T=!1,w;return w=R(I=>{if(!T)return w?w.dispose():T=!0,E.call(B,I)},null,A),T&&w.dispose(),w}}e.once=s;function r(R,E,B){return u((A,T=null,w)=>R(I=>A.call(T,E(I)),null,w),B)}e.map=r;function n(R,E,B){return u((A,T=null,w)=>R(I=>{E(I),A.call(T,I)},null,w),B)}e.forEach=n;function o(R,E,B){return u((A,T=null,w)=>R(I=>E(I)&&A.call(T,I),null,w),B)}e.filter=o;function l(R){return R}e.signal=l;function c(...R){return(E,B=null,A)=>{let T=Bd(...R.map(w=>w(I=>E.call(B,I))));return d(T,A)}}e.any=c;function a(R,E,B,A){let T=B;return r(R,w=>(T=E(T,w),T),A)}e.reduce=a;function u(R,E){let B,A={onWillAddFirstListener(){B=R(T.fire,T)},onDidRemoveLastListener(){B?.dispose()}};E||t(A);let T=new N(A);return E?.add(T),T.event}function d(R,E){return E instanceof Array?E.push(R):E&&E.add(R),R}function _(R,E,B=100,A=!1,T=!1,w,I){let P,re,Re,ee=0,fe,Ge={leakWarningThreshold:w,onWillAddFirstListener(){P=R(O=>{ee++,re=E(re,O),A&&!Re&&(le.fire(re),re=void 0),fe=()=>{let X=re;re=void 0,Re=void 0,(!A||ee>1)&&le.fire(X),ee=0},typeof B=="number"?(clearTimeout(Re),Re=setTimeout(fe,B)):Re===void 0&&(Re=0,queueMicrotask(fe))})},onWillRemoveListener(){T&&ee>0&&fe?.()},onDidRemoveLastListener(){fe=void 0,P.dispose()}};I||t(Ge);let le=new N(Ge);return I?.add(le),le.event}e.debounce=_;function m(R,E=0,B){return e.debounce(R,(A,T)=>A?(A.push(T),A):[T],E,void 0,!0,void 0,B)}e.accumulate=m;function p(R,E=(A,T)=>A===T,B){let A=!0,T;return o(R,w=>{let I=A||!E(w,T);return A=!1,T=w,I},B)}e.latch=p;function g(R,E,B){return[e.filter(R,E,B),e.filter(R,A=>!E(A),B)]}e.split=g;function y(R,E=!1,B=[],A){let T=B.slice(),w=R(re=>{T?T.push(re):P.fire(re)});A&&A.add(w);let I=()=>{T?.forEach(re=>P.fire(re)),T=null},P=new N({onWillAddFirstListener(){w||(w=R(re=>P.fire(re)),A&&A.add(w))},onDidAddFirstListener(){T&&(E?setTimeout(I):I())},onDidRemoveLastListener(){w&&w.dispose(),w=null}});return A&&A.add(P),P.event}e.buffer=y;function x(R,E){return(B,A,T)=>{let w=E(new W);return R(function(I){let P=w.evaluate(I);P!==q&&B.call(A,P)},void 0,T)}}e.chain=x;let q=Symbol("HaltChainable");class W{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(B=>(E(B),B)),this}filter(E){return this.steps.push(B=>E(B)?B:q),this}reduce(E,B){let A=B;return this.steps.push(T=>(A=E(A,T),A)),this}latch(E=(B,A)=>B===A){let B=!0,A;return this.steps.push(T=>{let w=B||!E(T,A);return B=!1,A=T,w?T:q}),this}evaluate(E){for(let B of this.steps)if(E=B(E),E===q)break;return E}}function k(R,E,B=A=>A){let A=(...P)=>I.fire(B(...P)),T=()=>R.on(E,A),w=()=>R.removeListener(E,A),I=new N({onWillAddFirstListener:T,onDidRemoveLastListener:w});return I.event}e.fromNodeEventEmitter=k;function M(R,E,B=A=>A){let A=(...P)=>I.fire(B(...P)),T=()=>R.addEventListener(E,A),w=()=>R.removeEventListener(E,A),I=new N({onWillAddFirstListener:T,onDidRemoveLastListener:w});return I.event}e.fromDOMEventEmitter=M;function Z(R){return new Promise(E=>s(R)(E))}e.toPromise=Z;function K(R){let E=new N;return R.then(B=>{E.fire(B)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=K;function ye(R,E){return R(B=>E.fire(B))}e.forward=ye;function ce(R,E,B){return E(B),R(A=>E(A))}e.runAndSubscribe=ce;class he{constructor(E,B){this._observable=E,this._counter=0,this._hasChanged=!1;let A={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};B||t(A),this.emitter=new N(A),B&&B.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,B){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function G(R,E){return new he(R,E).emitter.event}e.fromObservable=G;function ke(R){return(E,B,A)=>{let T=0,w=!1,I={beginUpdate(){T++},endUpdate(){T--,T===0&&(R.reportChanges(),w&&(w=!1,E.call(B)))},handlePossibleChange(){},handleChange(){w=!0}};R.addObserver(I),R.reportChanges();let P={dispose(){R.removeObserver(I)}};return A instanceof gi?A.add(P):Array.isArray(A)&&A.push(P),P}}e.fromObservableLight=ke})(ht||(ht={}));var Gn=class Xn{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Xn._idPool++}`,Xn.all.add(this)}start(t){this._stopWatch=new Pd,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Gn.all=new Set,Gn._idPool=0;var Nd=Gn,Za=-1,dc=class uc{constructor(t,i,s=(uc._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,i){let s=this.threshold;if(s<=0||i<s)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[n,o]=this.getMostFrequentStack(),l=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${o}):`;console.warn(l),console.warn(n);let c=new Hd(l,n);this._errorHandler(c)}return()=>{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,r]of this._stacks)(!t||i<r)&&(t=[s,r],i=r);return t}};dc._idPool=1;var Fd=dc,Jn=class fc{constructor(t){this.value=t}static create(){let t=new Error;return new fc(t.stack??"")}print(){console.warn(this.value.split(`
|
|
46
46
|
`).slice(2).join(`
|
|
47
|
-
`))}},
|
|
48
|
-
`)),e.length=0)},3e3),
|
|
47
|
+
`))}},Hd=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},Wd=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},zd=0,mr=class{constructor(e){this.value=e,this.id=zd++}},$d=2,Kd=(e,t)=>{if(e instanceof mr)t(e);else for(let i=0;i<e.length;i++){let s=e[i];s&&t(s)}},gr;if(Id){let e=[];setInterval(()=>{e.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(e.join(`
|
|
48
|
+
`)),e.length=0)},3e3),gr=new FinalizationRegistry(t=>{typeof t=="string"&&e.push(t)})}var N=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Za>0||this._options?.leakWarningThreshold?new Fd(e?.onListenerError??_r,this._options?.leakWarningThreshold??Za):void 0,this._perfMon=this._options?._profName?new Nd(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Ja){let e=this._listeners;queueMicrotask(()=>{Kd(e,t=>t.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??(this._event=(e,t,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let c=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],a=new Wd(`${l}. HINT: Stack shows most frequent listener (${c[1]}-times)`,c[0]);return(this._options?.onListenerError||_r)(a),ve.None}if(this._disposed)return ve.None;t&&(e=e.bind(t));let s=new mr(e),r,n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(s.stack=Jn.create(),r=this._leakageMon.check(s.stack,this._size+1)),Ja&&(s.stack=n??Jn.create()),this._listeners?this._listeners instanceof mr?(this._deliveryQueue??(this._deliveryQueue=new Ud),this._listeners=[this._listeners,s]):this._listeners.push(s):(this._options?.onWillAddFirstListener?.(this),this._listeners=s,this._options?.onDidAddFirstListener?.(this)),this._size++;let o=Be(()=>{gr?.unregister(o),r?.(),this._removeListener(s)});if(i instanceof gi?i.add(o):Array.isArray(i)&&i.push(o),gr){let l=new Error().stack.split(`
|
|
49
49
|
`).slice(2,3).join(`
|
|
50
|
-
`).trim(),h=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(l);Js.register(o,h?.[2]??l,o)}return o}),this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;let s=this._deliveryQueue.current===this;if(this._size*Hd<=t.length){let r=0;for(let n=0;n<t.length;n++)t[n]?t[r++]=t[n]:s&&(this._deliveryQueue.end--,r<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=r}}_deliver(e,t){if(!e)return;let i=this._options?.onListenerError||Gs;if(!i){e.value(t);return}try{e.value(t)}catch(s){i(s)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Xs)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},zd=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},An=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new N,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new N,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};An.INSTANCE=new An;var ao=An;function $d(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}var O_=ao.INSTANCE.onDidChangeZoomLevel;function Kd(e){return ao.INSTANCE.getZoomFactor(e)}var N_=ao.INSTANCE.onDidChangeFullscreen,Mi=typeof navigator=="object"?navigator.userAgent:"",Mn=Mi.indexOf("Firefox")>=0,Zs=Mi.indexOf("AppleWebKit")>=0,lo=Mi.indexOf("Chrome")>=0,Ql=!lo&&Mi.indexOf("Safari")>=0,F_=Mi.indexOf("Electron/")>=0,H_=Mi.indexOf("Android")>=0,Qs=!1;if(typeof wt.matchMedia=="function"){let e=wt.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=wt.matchMedia("(display-mode: fullscreen)");Qs=e.matches,$d(wt,e,({matches:i})=>{Qs&&t.matches||(Qs=i)})}function Ud(){return Qs}var Bi="en",rr=!1,nr=!1,os=!1,qd=!1,eh=!1,th=!1,Vd=!1,jd=!1,Yd=!1,Gd=!1,Us,er=Bi,Fa=Bi,Xd,Kt,qt=globalThis,bt;typeof qt.vscode<"u"&&typeof qt.vscode.process<"u"?bt=qt.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(bt=process);var ih=typeof bt?.versions?.electron=="string",Jd=ih&&bt?.type==="renderer";if(typeof bt=="object"){rr=bt.platform==="win32",nr=bt.platform==="darwin",os=bt.platform==="linux",qd=os&&!!bt.env.SNAP&&!!bt.env.SNAP_REVISION,Vd=ih,Yd=!!bt.env.CI||!!bt.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Us=Bi,er=Bi;let e=bt.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Us=t.userLocale,Fa=t.osLocale,er=t.resolvedLanguage||Bi,Xd=t.languagePack?.translationsConfigFile}catch{}eh=!0}else typeof navigator=="object"&&!Jd?(Kt=navigator.userAgent,rr=Kt.indexOf("Windows")>=0,nr=Kt.indexOf("Macintosh")>=0,jd=(Kt.indexOf("Macintosh")>=0||Kt.indexOf("iPad")>=0||Kt.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,os=Kt.indexOf("Linux")>=0,Gd=Kt?.indexOf("Mobi")>=0,th=!0,er=globalThis._VSCODE_NLS_LANGUAGE||Bi,Us=navigator.language.toLowerCase(),Fa=Us):console.error("Unable to resolve platform.");var tn=0;nr?tn=1:rr?tn=3:os&&(tn=2);var sh=rr,Ft=nr,Zd=os,sn=eh,Qd=th&&typeof qt.importScripts=="function",W_=Qd?qt.origin:void 0,Ht=Kt,Jt=er,Ha;(e=>{function t(){return Jt}e.value=t;function i(){return Jt.length===2?Jt==="en":Jt.length>=3?Jt[0]==="e"&&Jt[1]==="n"&&Jt[2]==="-":!1}e.isDefaultVariant=i;function s(){return Jt==="en"}e.isDefault=s})(Ha||(Ha={}));var eu=typeof qt.postMessage=="function"&&!qt.importScripts,tu=(()=>{if(eu){let e=[];qt.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,r=e.length;s<r;s++){let n=e[s];if(n.id===i.data.vscodeScheduleAsyncWork){e.splice(s,1),n.callback();return}}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),qt.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})(),iu=!!(Ht&&Ht.indexOf("Chrome")>=0),z_=!!(Ht&&Ht.indexOf("Firefox")>=0),$_=!!(!iu&&Ht&&Ht.indexOf("Safari")>=0),K_=!!(Ht&&Ht.indexOf("Edg/")>=0),U_=!!(Ht&&Ht.indexOf("Android")>=0),Zt=typeof navigator=="object"?navigator:{},q_={clipboard:{writeText:sn||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(Zt&&Zt.clipboard&&Zt.clipboard.writeText),readText:sn||!!(Zt&&Zt.clipboard&&Zt.clipboard.readText)},keyboard:sn||Ud()?0:Zt.keyboard||Ql?1:2,touch:"ontouchstart"in wt||Zt.maxTouchPoints>0,pointerEvents:wt.PointerEvent&&("ontouchstart"in wt||navigator.maxTouchPoints>0)},ho=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},rn=new ho,Wa=new ho,za=new ho,su=new Array(230),Pn;(e=>{function t(l){return rn.keyCodeToStr(l)}e.toString=t;function i(l){return rn.strToKeyCode(l)}e.fromString=i;function s(l){return Wa.keyCodeToStr(l)}e.toUserSettingsUS=s;function r(l){return za.keyCodeToStr(l)}e.toUserSettingsGeneral=r;function n(l){return Wa.strToKeyCode(l)||za.strToKeyCode(l)}e.fromUserSettings=n;function o(l){if(l>=98&&l<=113)return null;switch(l){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return rn.keyCodeToStr(l)}e.toElectronAccelerator=o})(Pn||(Pn={}));var ru=class rh{constructor(t,i,s,r,n){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=r,this.keyCode=n}equals(t){return t instanceof rh&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${i}${s}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new nu([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},nu=class{constructor(e){if(e.length===0)throw gd("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;t++)t!==0&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function ou(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return Pn.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Mn)switch(t){case 59:return 85;case 60:if(Zd)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ft)return 57;break}else if(Zs&&(Ft&&t===93||!Ft&&t===92))return 57;return su[t]||0}var au=Ft?256:2048,lu=512,hu=1024,cu=Ft?2048:256,In=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.("AltGraph"),this.keyCode=ou(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=au),this.altKey&&(t|=lu),this.shiftKey&&(t|=hu),this.metaKey&&(t|=cu),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new ru(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},$a=new WeakMap;function du(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var uu=class{static getSameOriginWindowChain(e){let t=$a.get(e);if(!t){t=[],$a.set(e,t);let i=e,s;do s=du(i),s?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=s;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let o=n.window.deref();if(i+=o?.scrollY??0,s+=o?.scrollX??0,o===t||!n.iframeElement)break;let l=n.iframeElement.getBoundingClientRect();i+=l.top,s+=l.left}return{top:i,left:s}}},es=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type==="dblclick"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX=="number"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=uu.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Ka=class{constructor(e,t=0,i=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let s=!1;if(lo){let r=navigator.userAgent.match(/Chrome\/(\d+)/);s=(r?parseInt(r[1]):123)<=122}if(e){let r=e,n=e,o=e.view?.devicePixelRatio||1;if(typeof r.wheelDeltaY<"u")s?this.deltaY=r.wheelDeltaY/(120*o):this.deltaY=r.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<"u"&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type==="wheel"){let l=e;l.deltaMode===l.DOM_DELTA_LINE?Mn&&!Ft?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof r.wheelDeltaX<"u")Ql&&sh?this.deltaX=-(r.wheelDeltaX/120):s?this.deltaX=r.wheelDeltaX/(120*o):this.deltaX=r.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<"u"&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let l=e;l.deltaMode===l.DOM_DELTA_LINE?Mn&&!Ft?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(s?this.deltaY=e.wheelDelta/(120*o):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},nh=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),Ua;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof fu?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:rt.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:nh})})(Ua||(Ua={}));var fu=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?nh:(this._emitter||(this._emitter=new N),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var co=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Cn("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Cn("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},pu=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Cn("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Te(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},_u,nn;(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?nn=(e,t)=>{tu(()=>{if(i)return;let s=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,s-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:nn=(e,t,i)=>{let s=e.requestIdleCallback(t,typeof i=="number"?{timeout:i}:void 0),r=!1;return{dispose(){r||(r=!0,e.cancelIdleCallback(s))}}},_u=e=>nn(globalThis,e)})();var qa;(e=>{async function t(s){let r,n=await Promise.all(s.map(o=>o.then(l=>l,l=>{r||(r=l)})));if(typeof r<"u")throw r;return n}e.settled=t;function i(s){return new Promise(async(r,n)=>{try{await s(r,n)}catch(o){n(o)}})}e.withAsyncBody=i})(qa||(qa={}));var Va=class kt{static fromArray(t){return new kt(i=>{i.emitMany(t)})}static fromPromise(t){return new kt(async i=>{i.emitMany(await t)})}static fromPromises(t){return new kt(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new kt(async i=>{await Promise.all(t.map(async s=>{for await(let r of s)i.emitOne(r)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new N,queueMicrotask(async()=>{let s={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(s)),this.resolve()}catch(r){this.reject(r)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await rt.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,i){return new kt(async s=>{for await(let r of t)s.emitOne(i(r))})}map(t){return kt.map(this,t)}static filter(t,i){return new kt(async s=>{for await(let r of t)i(r)&&s.emitOne(r)})}filter(t){return kt.filter(this,t)}static coalesce(t){return kt.filter(t,i=>!!i)}coalesce(){return kt.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return kt.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Va.EMPTY=Va.fromArray([]);function mu(e){return 55296<=e&&e<=56319}function ja(e){return 56320<=e&&e<=57343}function gu(e,t){return(e-55296<<10)+(t-56320)+65536}function vu(e){return uo(e,0)}function uo(e,t){switch(typeof e){case"object":return e===null?Ut(349,t):Array.isArray(e)?Su(e,t):bu(e,t);case"string":return oh(e,t);case"boolean":return yu(e,t);case"number":return Ut(e,t);case"undefined":return Ut(937,t);default:return Ut(617,t)}}function Ut(e,t){return(t<<5)-t+e|0}function yu(e,t){return Ut(e?433:863,t)}function oh(e,t){t=Ut(149417,t);for(let i=0,s=e.length;i<s;i++)t=Ut(e.charCodeAt(i),t);return t}function Su(e,t){return t=Ut(104579,t),e.reduce((i,s)=>uo(s,i),t)}function bu(e,t){return t=Ut(181387,t),Object.keys(e).sort().reduce((i,s)=>(i=oh(s,i),uo(e[s],i)),t)}function on(e,t,i=32){let s=i-t,r=~((1<<s)-1);return(e<<t|(r&e)>>>s)>>>0}function Ya(e,t=0,i=e.byteLength,s=0){for(let r=0;r<i;r++)e[t+r]=s}function wu(e,t,i="0"){for(;e.length<t;)e=i+e;return e}function ji(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(i=>i.toString(16).padStart(2,"0")).join(""):wu((e>>>0).toString(16),t/4)}var Cu=class ah{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let i=t.length;if(i===0)return;let s=this._buff,r=this._buffLen,n=this._leftoverHighSurrogate,o,l;for(n!==0?(o=n,l=-1,n=0):(o=t.charCodeAt(0),l=0);;){let h=o;if(mu(o))if(l+1<i){let a=t.charCodeAt(l+1);ja(a)?(l++,h=gu(o,a)):h=65533}else{n=o;break}else ja(o)&&(h=65533);if(r=this._push(s,r,h),l++,l<i)o=t.charCodeAt(l);else break}this._buffLen=r,this._leftoverHighSurrogate=n}_push(t,i,s){return s<128?t[i++]=s:s<2048?(t[i++]=192|(s&1984)>>>6,t[i++]=128|(s&63)>>>0):s<65536?(t[i++]=224|(s&61440)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0):(t[i++]=240|(s&1835008)>>>18,t[i++]=128|(s&258048)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0),i>=64&&(this._step(),i-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),i}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),ji(this._h0)+ji(this._h1)+ji(this._h2)+ji(this._h3)+ji(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,Ya(this._buff,this._buffLen),this._buffLen>56&&(this._step(),Ya(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=ah._bigBlock32,i=this._buffDV;for(let d=0;d<64;d+=4)t.setUint32(d,i.getUint32(d,!1),!1);for(let d=64;d<320;d+=4)t.setUint32(d,on(t.getUint32(d-12,!1)^t.getUint32(d-32,!1)^t.getUint32(d-56,!1)^t.getUint32(d-64,!1),1),!1);let s=this._h0,r=this._h1,n=this._h2,o=this._h3,l=this._h4,h,a,u;for(let d=0;d<80;d++)d<20?(h=r&n|~r&o,a=1518500249):d<40?(h=r^n^o,a=1859775393):d<60?(h=r&n|r&o|n&o,a=2400959708):(h=r^n^o,a=3395469782),u=on(s,5)+h+l+a+t.getUint32(d*4,!1)&4294967295,l=o,o=n,n=on(r,30),r=s,s=u;this._h0=this._h0+s&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+n&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+l&4294967295}};Cu._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:V_,getWindow:Mt,getDocument:j_,getWindows:Y_,getWindowsCount:G_,getWindowId:Ga,getWindowById:X_,hasWindow:J_,onDidRegisterWindow:xu,onWillUnregisterWindow:Z_,onDidUnregisterWindow:Q_}=(function(){let e=new Map,t={window:wt,disposables:new si};e.set(wt.vscodeWindowId,t);let i=new N,s=new N,r=new N;function n(o,l){return(typeof o=="number"?e.get(o):void 0)??(l?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(o){if(e.has(o.vscodeWindowId))return he.None;let l=new si,h={window:o,disposables:l.add(new si)};return e.set(o.vscodeWindowId,h),l.add(Te(()=>{e.delete(o.vscodeWindowId),s.fire(o)})),l.add(ie(o,et.BEFORE_UNLOAD,()=>{r.fire(o)})),i.fire(h),l},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){let l=o;if(l?.ownerDocument?.defaultView)return l.ownerDocument.defaultView.window;let h=o;return h?.view?h.view.window:wt},getDocument(o){return Mt(o).document}}})(),ku=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function ie(e,t,i,s){return new ku(e,t,i,s)}function Eu(e,t){return function(i){return t(new es(e,i))}}function Ru(e){return function(t){return e(new In(t))}}var Xa=function(e,t,i,s){let r=i;return t==="click"||t==="mousedown"||t==="contextmenu"?r=Eu(Mt(e),i):(t==="keydown"||t==="keypress"||t==="keyup")&&(r=Ru(i)),ie(e,t,r,s)},Tu,or,Du=class extends pu{constructor(e){super(),this.defaultTarget=e&&Mt(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},an=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Gs(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,r=n=>{i.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),s.set(n,!0);o.length>0;)o.sort(an.sort),o.shift().execute();s.set(n,!1)};or=(n,o,l=0)=>{let h=Ga(n),a=new an(o,l),u=e.get(h);return u||(u=[],e.set(h,u)),u.push(a),i.get(h)||(i.set(h,!0),n.requestAnimationFrame(()=>r(h))),a},Tu=(n,o,l)=>{let h=Ga(n);if(s.get(h)){let a=new an(o,l),u=t.get(h);return u||(u=[],t.set(h,u)),u.push(a),a}else return or(n,o,l)}})();var Ja=class tr{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new tr(t,i):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof tr?t:new tr(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};Ja.None=new Ja(0,0);function Bu(e){let t=e.getBoundingClientRect(),i=Mt(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var em=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let s=this.mutationObservers.get(e);s||(s=new Map,this.mutationObservers.set(e,s));let r=vu(i),n=s.get(r);if(n)n.users+=1;else{let o=new N,l=new MutationObserver(a=>o.fire(a));l.observe(e,i);let h=n={users:1,observer:l,onDidMutate:o.event};t.add(Te(()=>{h.users-=1,h.users===0&&(o.dispose(),l.disconnect(),s?.delete(r),s?.size===0&&this.mutationObservers.delete(e))})),s.set(r,n)}return n.onDidMutate}},et={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:Zs?"webkitAnimationStart":"animationstart",ANIMATION_END:Zs?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:Zs?"webkitAnimationIteration":"animationiteration"},Lu=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function lh(e,t,i,...s){let r=Lu.exec(t);if(!r)throw new Error("Bad use of emmet");let n=r[1]||"div",o;return e!=="http://www.w3.org/1999/xhtml"?o=document.createElementNS(e,n):o=document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\./g," ").trim()),i&&Object.entries(i).forEach(([l,h])=>{typeof h>"u"||(/^on\w+$/.test(l)?o[l]=h:l==="selected"?h&&o.setAttribute(l,"true"):o.setAttribute(l,h))}),o.append(...s),o}function Au(e,t,...i){return lh("http://www.w3.org/1999/xhtml",e,t,...i)}Au.SVG=function(e,t,...i){return lh("http://www.w3.org/2000/svg",e,t,...i)};var Mu=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=_t(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=_t(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=_t(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=_t(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=_t(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=_t(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=_t(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=_t(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=_t(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=_t(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=_t(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=_t(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=_t(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=_t(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function _t(e){return typeof e=="number"?`${e}px`:e}function as(e){return new Mu(e)}var hh=class{constructor(){this._hooks=new si,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(Te(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=Mt(e)}this._hooks.add(ie(n,et.POINTER_MOVE,o=>{if(o.buttons!==i){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(ie(n,et.POINTER_UP,o=>this.stopMonitoring(!0)))}};function Pu(e,t,i){let s=null,r=null;if(typeof i.value=="function"?(s="value",r=i.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",r=i.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;i[s]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var At;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(At||(At={}));var ts=class ht extends he{constructor(){super(),this.dispatched=!1,this.targets=new Ia,this.ignoreTargets=new Ia,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(rt.runAndSubscribe(xu,({window:t,disposables:i})=>{i.add(ie(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(ie(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(ie(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:wt,disposables:this._store}))}static addTarget(t){if(!ht.isTouchDevice())return he.None;ht.INSTANCE||(ht.INSTANCE=Pa(new ht));let i=ht.INSTANCE.targets.push(t);return Te(i)}static ignoreTarget(t){if(!ht.isTouchDevice())return he.None;ht.INSTANCE||(ht.INSTANCE=Pa(new ht));let i=ht.INSTANCE.ignoreTargets.push(t);return Te(i)}static isTouchDevice(){return"ontouchstart"in wt||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,r=t.targetTouches.length;s<r;s++){let n=t.targetTouches.item(s);this.activeTouches[n.identifier]={id:n.identifier,initialTarget:n.target,initialTimeStamp:i,initialPageX:n.pageX,initialPageY:n.pageY,rollingTimestamps:[i],rollingPageX:[n.pageX],rollingPageY:[n.pageY]};let o=this.newGestureEvent(At.Start,n.target);o.pageX=n.pageX,o.pageY=n.pageY,this.dispatchEvent(o)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let l=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(l.identifier))){console.warn("move of an UNKNOWN touch",l);continue}let h=this.activeTouches[l.identifier],a=Date.now()-h.initialTimeStamp;if(a<ht.HOLD_DELAY&&Math.abs(h.initialPageX-yt(h.rollingPageX))<30&&Math.abs(h.initialPageY-yt(h.rollingPageY))<30){let u=this.newGestureEvent(At.Tap,h.initialTarget);u.pageX=yt(h.rollingPageX),u.pageY=yt(h.rollingPageY),this.dispatchEvent(u)}else if(a>=ht.HOLD_DELAY&&Math.abs(h.initialPageX-yt(h.rollingPageX))<30&&Math.abs(h.initialPageY-yt(h.rollingPageY))<30){let u=this.newGestureEvent(At.Contextmenu,h.initialTarget);u.pageX=yt(h.rollingPageX),u.pageY=yt(h.rollingPageY),this.dispatchEvent(u)}else if(r===1){let u=yt(h.rollingPageX),d=yt(h.rollingPageY),m=yt(h.rollingTimestamps)-h.rollingTimestamps[0],p=u-h.rollingPageX[0],_=d-h.rollingPageY[0],g=[...this.targets].filter(y=>h.initialTarget instanceof Node&&y.contains(h.initialTarget));this.inertia(t,g,s,Math.abs(p)/m,p>0?1:-1,u,Math.abs(_)/m,_>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(At.End,h.initialTarget)),delete this.activeTouches[l.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===At.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>ht.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===At.Change||t.type===At.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let r=0,n=t.initialTarget;for(;n&&n!==s;)r++,n=n.parentElement;i.push([r,s])}i.sort((s,r)=>s[0]-r[0]);for(let[s,r]of i)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,l,h,a){this.handle=or(t,()=>{let u=Date.now(),d=u-s,m=0,p=0,_=!0;r+=ht.SCROLL_FRICTION*d,l+=ht.SCROLL_FRICTION*d,r>0&&(_=!1,m=n*r*d),l>0&&(_=!1,p=h*l*d);let g=this.newGestureEvent(At.Change);g.translationX=m,g.translationY=p,i.forEach(y=>y.dispatchEvent(g)),_||this.inertia(t,i,u,r,n,o+m,l,h,a+p)})}onTouchMove(t){let i=Date.now();for(let s=0,r=t.changedTouches.length;s<r;s++){let n=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(n.identifier))){console.warn("end of an UNKNOWN touch",n);continue}let o=this.activeTouches[n.identifier],l=this.newGestureEvent(At.Change,o.initialTarget);l.translationX=n.pageX-yt(o.rollingPageX),l.translationY=n.pageY-yt(o.rollingPageY),l.pageX=n.pageX,l.pageY=n.pageY,this.dispatchEvent(l),o.rollingPageX.length>3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};ts.SCROLL_FRICTION=-.005,ts.HOLD_DELAY=700,ts.CLEAR_TAP_COUNT_TIME=400,He([Pu],ts,"isTouchDevice",1);var Iu=ts,fo=class extends he{onclick(e,t){this._register(ie(e,et.CLICK,i=>t(new es(Mt(e),i))))}onmousedown(e,t){this._register(ie(e,et.MOUSE_DOWN,i=>t(new es(Mt(e),i))))}onmouseover(e,t){this._register(ie(e,et.MOUSE_OVER,i=>t(new es(Mt(e),i))))}onmouseleave(e,t){this._register(ie(e,et.MOUSE_LEAVE,i=>t(new es(Mt(e),i))))}onkeydown(e,t){this._register(ie(e,et.KEY_DOWN,i=>t(new In(i))))}onkeyup(e,t){this._register(ie(e,et.KEY_UP,i=>t(new In(i))))}oninput(e,t){this._register(ie(e,et.INPUT,t))}onblur(e,t){this._register(ie(e,et.BLUR,t))}onfocus(e,t){this._register(ie(e,et.FOCUS,t))}onchange(e,t){this._register(ie(e,et.CHANGE,t))}ignoreGesture(e){return Iu.ignoreTarget(e)}},Za=11,Ou=class extends fo{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Za+"px",this.domNode.style.height=Za+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new hh),this._register(Xa(this.bgDomNode,et.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Xa(this.domNode,et.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Du),this._pointerdownScheduleRepeatTimer=this._register(new co)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Mt(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Nu=class On{constructor(t,i,s,r,n,o,l){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,r=r|0,n=n|0,o=o|0,l=l|0),this.rawScrollLeft=r,this.rawScrollTop=l,i<0&&(i=0),r+i>s&&(r=s-i),r<0&&(r=0),n<0&&(n=0),l+n>o&&(l=o-n),l<0&&(l=0),this.width=i,this.scrollWidth=s,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=l}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new On(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new On(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,l=this.scrollHeight!==t.scrollHeight,h=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:l,scrollTopChanged:h}}},Fu=class extends he{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Nu(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new el(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=el.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Qa=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function ln(e,t){let i=t-e;return function(s){return e+i*zu(s)}}function Hu(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}var el=class Nn{constructor(t,i,s,r){this.from=t,this.to=i,this.duration=r,this.startTime=s,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,i,s){if(Math.abs(t-i)>2.5*s){let r,n;return t<i?(r=t+.75*s,n=i-.75*s):(r=t-.75*s,n=i+.75*s),Hu(ln(t,r),ln(n,i),.33)}return ln(t,i)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let i=(t-this.startTime)/this.duration;if(i<1){let s=this.scrollLeft(i),r=this.scrollTop(i);return new Qa(s,r,!1)}return new Qa(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return Nn.start(t,i,s)}static start(t,i,s){s=s+10;let r=Date.now()-10;return new Nn(t,i,r,s)}};function Wu(e){return Math.pow(e,3)}function zu(e){return 1-Wu(1-e)}var $u=class extends he{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new co)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},Ku=140,ch=class extends fo{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new $u(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new hh),this._shouldRender=!0,this.domNode=as(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(ie(this.domNode.domNode,et.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Ou(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=as(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(ie(this.slider.domNode,et.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let r=Bu(this.domNode.domNode);t=e.pageX-r.left,i=e.pageY-r.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let n=this._sliderOrthogonalPointerPosition(r),o=Math.abs(n-i);if(sh&&o>Ku){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let l=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(l))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},dh=class Fn{constructor(t,i,s,r,n,o){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new Fn(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,r,n){let o=Math.max(0,s-t),l=Math.max(0,o-2*i),h=r>0&&r>s;if(!h)return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(l),computedSliderRatio:0,computedSliderPosition:0};let a=Math.round(Math.max(20,Math.floor(s*l/r))),u=(l-a)/(r-s),d=n*u;return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(a),computedSliderRatio:u,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=Fn._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},Uu=class extends ch{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new dh(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},qu=class extends ch{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new dh(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Vu=500,tl=50,il=!0,ju=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Hn=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,i=0,s=1,r=this._rear;do{let n=r===this._front?t:Math.pow(2,-s);if(t-=n,i+=this._memory[r].score*n,r===this._front)break;r=(this._capacity+r-1)%this._capacity,s++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(lo){let i=Mt(t.browserEvent),s=Kd(i);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,s){let r=null,n=new ju(t,i,s);this._front===-1&&this._rear===-1?(this._memory[0]=n,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=n),n.score=this._computeScore(n,r)}_computeScore(t,i){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(i.deltaX),l=Math.abs(i.deltaY),h=Math.max(Math.min(r,o),1),a=Math.max(Math.min(n,l),1),u=Math.max(r,o),d=Math.max(n,l);u%h===0&&d%a===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Hn.INSTANCE=new Hn;var Yu=Hn,Gu=class extends fo{constructor(e,t,i){super(),this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new N),this.onWillScroll=this._onWillScroll.event,this._options=Ju(t),this._scrollable=i,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let s={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new qu(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Uu(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=as(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=as(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=as(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new co),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=mi(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Ft&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Ka(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=mi(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Ka(i))};this._mouseWheelToDispose.push(ie(this._listenOnDomNode,et.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Yu.INSTANCE;il&&t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,n=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&n+r===0?n=r=0:Math.abs(r)>=Math.abs(n)?n=0:r=0),this._options.flipAxes&&([r,n]=[n,r]);let o=!Ft&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||o)&&!n&&(n=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(n=n*this._options.fastScrollSensitivity,r=r*this._options.fastScrollSensitivity);let l=this._scrollable.getFutureScrollPosition(),h={};if(r){let a=tl*r,u=l.scrollTop-(a<0?Math.floor(a):Math.ceil(a));this._verticalScrollbar.writeScrollPosition(h,u)}if(n){let a=tl*n,u=l.scrollLeft-(a<0?Math.floor(a):Math.ceil(a));this._horizontalScrollbar.writeScrollPosition(h,u)}h=this._scrollable.validateScrollPosition(h),(l.scrollLeft!==h.scrollLeft||l.scrollTop!==h.scrollTop)&&(il&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(h):this._scrollable.setScrollPositionNow(h),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Vu)}},Xu=class extends Gu{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Ju(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Ft&&(t.className+=" mac"),t}var Wn=class extends he{constructor(e,t,i,s,r,n,o,l){super(),this._bufferService=i,this._optionsService=o,this._renderService=l,this._onRequestScrollLines=this._register(new N),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let h=this._register(new Fu({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:a=>or(s.window,a)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{h.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Xu(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},h)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(a=>{this._scrollableElement.updateOptions({handleMouseWheel:!(a&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(rt.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Te(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Te(()=>this._styleElement.remove())),this._register(rt.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
|
|
51
|
-
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(a=>this._handleScroll(a)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Wn=He([K(2,dt),K(3,Vt),K(4,Hl),K(5,Ai),K(6,ut),K(7,jt)],Wn);var zn=class extends he{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(n=>this._removeDecoration(n))),this._register(Te(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};zn=He([K(1,dt),K(2,Vt),K(3,_s),K(4,jt)],zn);var Zu=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Ot={full:0,left:0,center:0,right:0},Qt={full:0,left:0,center:0,right:0},Yi={full:0,left:0,center:0,right:0},ar=class extends he{constructor(e,t,i,s,r,n,o,l){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=l,this._colorZoneStore=new Zu,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(Te(()=>this._canvas?.remove()));let h=this._canvas.getContext("2d");if(h)this._ctx=h;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Qt.full=this._canvas.width,Qt.left=e,Qt.center=t,Qt.right=e,this._refreshDrawHeightConstants(),Yi.full=1,Yi.left=1,Yi.center=1+Qt.left,Yi.right=1+Qt.left+Qt.center}_refreshDrawHeightConstants(){Ot.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);Ot.left=t,Ot.center=t,Ot.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ot.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ot.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ot.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ot.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Yi[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Ot[e.position||"full"]/2),Qt[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Ot[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ar=He([K(2,dt),K(3,_s),K(4,jt),K(5,ut),K(6,Ai),K(7,Vt)],ar);var S;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=`
|
|
52
|
-
`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(S||(S={}));var ls;(e=>(e.PAD="",e.HOP="",e.BPH="",e.NBH="",e.IND="",e.NEL="
",e.SSA="",e.ESA="",e.HTS="",e.HTJ="",e.VTS="",e.PLD="",e.PLU="",e.RI="",e.SS2="",e.SS3="",e.DCS="",e.PU1="",e.PU2="",e.STS="",e.CCH="",e.MW="",e.SPA="",e.EPA="",e.SOS="",e.SGCI="",e.SCI="",e.CSI="",e.ST="",e.OSC="",e.PM="",e.APC=""))(ls||(ls={}));var $n;(e=>e.ST=`${S.ESC}\\`)($n||($n={}));var Kn=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${S.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),i=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+"px",this._compositionView.style.top=s+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let n=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+"px",this._textarea.style.top=s+"px",this._textarea.style.width=Math.max(n.width,1)+"px",this._textarea.style.height=Math.max(n.height,1)+"px",this._textarea.style.lineHeight=n.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};Kn=He([K(2,dt),K(3,ut),K(4,vi),K(5,jt)],Kn);var tt=0,it=0,st=0,Fe=0,sl={css:"#00000000",rgba:0},Ke;(e=>{function t(r,n,o,l){return l!==void 0?`#${di(r)}${di(n)}${di(o)}${di(l)}`:`#${di(r)}${di(n)}${di(o)}`}e.toCss=t;function i(r,n,o,l=255){return(r<<24|n<<16|o<<8|l)>>>0}e.toRgba=i;function s(r,n,o,l){return{css:e.toCss(r,n,o,l),rgba:e.toRgba(r,n,o,l)}}e.toColor=s})(Ke||(Ke={}));var Re;(e=>{function t(h,a){if(Fe=(a.rgba&255)/255,Fe===1)return{css:a.css,rgba:a.rgba};let u=a.rgba>>24&255,d=a.rgba>>16&255,m=a.rgba>>8&255,p=h.rgba>>24&255,_=h.rgba>>16&255,g=h.rgba>>8&255;tt=p+Math.round((u-p)*Fe),it=_+Math.round((d-_)*Fe),st=g+Math.round((m-g)*Fe);let y=Ke.toCss(tt,it,st),x=Ke.toRgba(tt,it,st);return{css:y,rgba:x}}e.blend=t;function i(h){return(h.rgba&255)===255}e.isOpaque=i;function s(h,a,u){let d=hs.ensureContrastRatio(h.rgba,a.rgba,u);if(d)return Ke.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=s;function r(h){let a=(h.rgba|255)>>>0;return[tt,it,st]=hs.toChannels(a),{css:Ke.toCss(tt,it,st),rgba:a}}e.opaque=r;function n(h,a){return Fe=Math.round(a*255),[tt,it,st]=hs.toChannels(h.rgba),{css:Ke.toCss(tt,it,st,Fe),rgba:Ke.toRgba(tt,it,st,Fe)}}e.opacity=n;function o(h,a){return Fe=h.rgba&255,n(h,Fe*a/255)}e.multiplyOpacity=o;function l(h){return[h.rgba>>24&255,h.rgba>>16&255,h.rgba>>8&255]}e.toColorRGB=l})(Re||(Re={}));var Be;(e=>{let t,i;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return tt=parseInt(r.slice(1,2).repeat(2),16),it=parseInt(r.slice(2,3).repeat(2),16),st=parseInt(r.slice(3,4).repeat(2),16),Ke.toColor(tt,it,st);case 5:return tt=parseInt(r.slice(1,2).repeat(2),16),it=parseInt(r.slice(2,3).repeat(2),16),st=parseInt(r.slice(3,4).repeat(2),16),Fe=parseInt(r.slice(4,5).repeat(2),16),Ke.toColor(tt,it,st,Fe);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return tt=parseInt(n[1]),it=parseInt(n[2]),st=parseInt(n[3]),Fe=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),Ke.toColor(tt,it,st,Fe);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=r,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[tt,it,st,Fe]=t.getImageData(0,0,1,1).data,Fe!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ke.toRgba(tt,it,st,Fe),css:r}}e.toColor=s})(Be||(Be={}));var ct;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,r,n){let o=s/255,l=r/255,h=n/255,a=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),d=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4);return a*.2126+u*.7152+d*.0722}e.relativeLuminance2=i})(ct||(ct={}));var hs;(e=>{function t(o,l){if(Fe=(l&255)/255,Fe===1)return l;let h=l>>24&255,a=l>>16&255,u=l>>8&255,d=o>>24&255,m=o>>16&255,p=o>>8&255;return tt=d+Math.round((h-d)*Fe),it=m+Math.round((a-m)*Fe),st=p+Math.round((u-p)*Fe),Ke.toRgba(tt,it,st)}e.blend=t;function i(o,l,h){let a=ct.relativeLuminance(o>>8),u=ct.relativeLuminance(l>>8);if($t(a,u)<h){if(u<a){let p=s(o,l,h),_=$t(a,ct.relativeLuminance(p>>8));if(_<h){let g=r(o,l,h),y=$t(a,ct.relativeLuminance(g>>8));return _>y?p:g}return p}let d=r(o,l,h),m=$t(a,ct.relativeLuminance(d>>8));if(m<h){let p=s(o,l,h),_=$t(a,ct.relativeLuminance(p>>8));return m>_?d:p}return d}}e.ensureContrastRatio=i;function s(o,l,h){let a=o>>24&255,u=o>>16&255,d=o>>8&255,m=l>>24&255,p=l>>16&255,_=l>>8&255,g=$t(ct.relativeLuminance2(m,p,_),ct.relativeLuminance2(a,u,d));for(;g<h&&(m>0||p>0||_>0);)m-=Math.max(0,Math.ceil(m*.1)),p-=Math.max(0,Math.ceil(p*.1)),_-=Math.max(0,Math.ceil(_*.1)),g=$t(ct.relativeLuminance2(m,p,_),ct.relativeLuminance2(a,u,d));return(m<<24|p<<16|_<<8|255)>>>0}e.reduceLuminance=s;function r(o,l,h){let a=o>>24&255,u=o>>16&255,d=o>>8&255,m=l>>24&255,p=l>>16&255,_=l>>8&255,g=$t(ct.relativeLuminance2(m,p,_),ct.relativeLuminance2(a,u,d));for(;g<h&&(m<255||p<255||_<255);)m=Math.min(255,m+Math.ceil((255-m)*.1)),p=Math.min(255,p+Math.ceil((255-p)*.1)),_=Math.min(255,_+Math.ceil((255-_)*.1)),g=$t(ct.relativeLuminance2(m,p,_),ct.relativeLuminance2(a,u,d));return(m<<24|p<<16|_<<8|255)>>>0}e.increaseLuminance=r;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(hs||(hs={}));function di(e){let t=e.toString(16);return t.length<2?"0"+t:t}function $t(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Qu=class extends ps{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},lr=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Rt}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let i=[],s=t.translateToString(!0),r=0,n=0,o=0,l=t.getFg(0),h=t.getBg(0);for(let a=0;a<t.getTrimmedLength();a++)if(t.loadCell(a,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==l||this._workCell.bg!==h){if(a-r>1){let u=this._getJoinedRanges(s,o,n,t,r);for(let d=0;d<u.length;d++)i.push(u[d])}r=a,o=n,l=this._workCell.fg,h=this._workCell.bg}n+=this._workCell.getChars().length||ii.length}if(this._bufferService.cols-r>1){let a=this._getJoinedRanges(s,o,n,t,r);for(let u=0;u<a.length;u++)i.push(a[u])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(l){console.error(l)}for(let l=1;l<this._characterJoiners.length;l++)try{let h=this._characterJoiners[l].handler(n);for(let a=0;a<h.length;a++)lr._mergeRanges(o,h[a])}catch(h){console.error(h)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let l=i;l<this._bufferService.cols;l++){let h=t.getWidth(l),a=t.getString(l).length||ii.length;if(h!==0){if(!r&&o[0]<=n&&(o[0]=l,r=!0),o[1]<=n){if(o[1]=l,o=e[++s],!o)break;o[0]<=n?(o[0]=l,r=!0):r=!1}n+=a}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};lr=He([K(0,dt)],lr);function ef(e){return 57508<=e&&e<=57558}function tf(e){return 9472<=e&&e<=9631}function sf(e){return ef(e)||tf(e)}function rf(){return{css:{canvas:qs(),cell:qs()},device:{canvas:qs(),cell:qs(),char:{width:0,height:0,left:0,top:0}}}}function qs(){return{width:0,height:0}}var Un=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new Rt,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,l,h,a,u){let d=[],m=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,_=e.getNoBgTrimmedLength();i&&_<n+1&&(_=n+1);let g,y=0,x="",j=0,z=0,C=0,O=0,X=!1,$=0,ye=!1,de=0,fe=0,Z=[],we=a!==-1&&u!==-1;for(let k=0;k<_;k++){e.loadCell(k,this._workCell);let E=this._workCell.getWidth();if(E===0)continue;let A=!1,L=k>=fe,T=k,b=this._workCell;if(m.length>0&&k===m[0][0]&&L){let re=m.shift(),Ct=this._isCellInSelection(re[0],t);for(j=re[0]+1;j<re[1];j++)L&&(L=Ct===this._isCellInSelection(j,t));L&&(L=!i||n<re[0]||n>=re[1]),L?(A=!0,b=new Qu(this._workCell,e.translateToString(!0,re[0],re[1]),re[1]-re[0]),T=re[1]-1,E=b.getWidth()):fe=re[1]}let M=this._isCellInSelection(k,t),B=i&&k===n,te=we&&k>=a&&k<=u,Se=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,re=>{Se=!0});let ne=b.getChars()||ii;if(ne===" "&&(b.isUnderline()||b.isOverline())&&(ne=" "),de=E*l-h.get(ne,b.isBold(),b.isItalic()),!g)g=this._document.createElement("span");else if(y&&(M&&ye||!M&&!ye&&b.bg===z)&&(M&&ye&&p.selectionForeground||b.fg===C)&&b.extended.ext===O&&te===X&&de===$&&!B&&!A&&!Se&&L){b.isInvisible()?x+=ii:x+=ne,y++;continue}else y&&(g.textContent=x),g=this._document.createElement("span"),y=0,x="";if(z=b.bg,C=b.fg,O=b.extended.ext,X=te,$=de,ye=M,A&&n>=k&&n<=T&&(n=k),!this._coreService.isCursorHidden&&B&&this._coreService.isCursorInitialized){if(Z.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&Z.push("xterm-cursor-blink"),Z.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":Z.push("xterm-cursor-outline");break;case"block":Z.push("xterm-cursor-block");break;case"bar":Z.push("xterm-cursor-bar");break;case"underline":Z.push("xterm-cursor-underline");break;default:break}}if(b.isBold()&&Z.push("xterm-bold"),b.isItalic()&&Z.push("xterm-italic"),b.isDim()&&Z.push("xterm-dim"),b.isInvisible()?x=ii:x=b.getChars()||ii,b.isUnderline()&&(Z.push(`xterm-underline-${b.extended.underlineStyle}`),x===" "&&(x=" "),!b.isUnderlineColorDefault()))if(b.isUnderlineColorRGB())g.style.textDecorationColor=`rgb(${ps.toColorRGB(b.getUnderlineColor()).join(",")})`;else{let re=b.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&b.isBold()&&re<8&&(re+=8),g.style.textDecorationColor=p.ansi[re].css}b.isOverline()&&(Z.push("xterm-overline"),x===" "&&(x=" ")),b.isStrikethrough()&&Z.push("xterm-strikethrough"),te&&(g.style.textDecoration="underline");let _e=b.getFgColor(),Oe=b.getFgColorMode(),se=b.getBgColor(),W=b.getBgColorMode(),q=!!b.isInverse();if(q){let re=_e;_e=se,se=re;let Ct=Oe;Oe=W,W=Ct}let le,vt,Ue=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,re=>{re.options.layer!=="top"&&Ue||(re.backgroundColorRGB&&(W=50331648,se=re.backgroundColorRGB.rgba>>8&16777215,le=re.backgroundColorRGB),re.foregroundColorRGB&&(Oe=50331648,_e=re.foregroundColorRGB.rgba>>8&16777215,vt=re.foregroundColorRGB),Ue=re.options.layer==="top")}),!Ue&&M&&(le=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,se=le.rgba>>8&16777215,W=50331648,Ue=!0,p.selectionForeground&&(Oe=50331648,_e=p.selectionForeground.rgba>>8&16777215,vt=p.selectionForeground)),Ue&&Z.push("xterm-decoration-top");let ot;switch(W){case 16777216:case 33554432:ot=p.ansi[se],Z.push(`xterm-bg-${se}`);break;case 50331648:ot=Ke.toColor(se>>16,se>>8&255,se&255),this._addStyle(g,`background-color:#${rl((se>>>0).toString(16),"0",6)}`);break;default:q?(ot=p.foreground,Z.push("xterm-bg-257")):ot=p.background}switch(le||b.isDim()&&(le=Re.multiplyOpacity(ot,.5)),Oe){case 16777216:case 33554432:b.isBold()&&_e<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(_e+=8),this._applyMinimumContrast(g,ot,p.ansi[_e],b,le,void 0)||Z.push(`xterm-fg-${_e}`);break;case 50331648:let re=Ke.toColor(_e>>16&255,_e>>8&255,_e&255);this._applyMinimumContrast(g,ot,re,b,le,vt)||this._addStyle(g,`color:#${rl(_e.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(g,ot,p.foreground,b,le,vt)||q&&Z.push("xterm-fg-257")}Z.length&&(g.className=Z.join(" "),Z.length=0),!B&&!A&&!Se&&L?y++:g.textContent=x,de!==this.defaultSpacing&&(g.style.letterSpacing=`${de}px`),d.push(g),k=T}return g&&y&&(g.textContent=x),d}_applyMinimumContrast(e,t,i,s,r,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||sf(s.getCode()))return!1;let o=this._getContrastCache(s),l;if(!r&&!n&&(l=o.getColor(t.rgba,i.rgba)),l===void 0){let h=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);l=Re.ensureContrastRatio(r||t,n||i,h),o.setColor((r||t).rgba,(n||i).rgba,l??null)}return l?(this._addStyle(e,`color:${l.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0]}};Un=He([K(1,$l),K(2,ut),K(3,Vt),K(4,vi),K(5,_s),K(6,Ai)],Un);function rl(e,t,i){for(;e.length<i;)e=t+e;return e}var nf=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&e.length===1&&(s=e.charCodeAt(0))<256){if(this._flat[s]!==-9999)return this._flat[s];let o=this._measure(e,0);return o>0&&(this._flat[s]=o),o}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(n===void 0){let o=0;t&&(o|=1),i&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},of=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,l=Math.max(n,0),h=Math.min(o,e.rows-1);if(l>=e.rows||h<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=l,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function af(){return new of}var hn="xterm-dom-renderer-owner-",xt="xterm-rows",Vs="xterm-fg-",nl="xterm-bg-",Gi="xterm-focus",js="xterm-selection",lf=1,qn=class extends he{constructor(e,t,i,s,r,n,o,l,h,a,u,d,m,p){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=h,this._optionsService=a,this._bufferService=u,this._coreService=d,this._coreBrowserService=m,this._themeService=p,this._terminalClass=lf++,this._rowElements=[],this._selectionRenderModel=af(),this.onRequestRedraw=this._register(new N).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(xt),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(js),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=rf(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(_=>this._injectCss(_))),this._injectCss(this._themeService.colors),this._rowFactory=l.createInstance(Un,document),this._element.classList.add(hn+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(_=>this._handleLinkHover(_))),this._register(this._linkifier2.onHideLinkUnderline(_=>this._handleLinkLeave(_))),this._register(Te(()=>{this._element.classList.remove(hn+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new nf(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${xt} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${xt} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${xt} .xterm-dim { color: ${Re.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${xt}.${Gi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${xt}.${Gi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${xt}.${Gi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${xt} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${xt} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${xt} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${xt} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${xt} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${js} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${js} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${js} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${Vs}${n} { color: ${o.css}; }${this._terminalSelector} .${Vs}${n}.xterm-dim { color: ${Re.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${nl}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${Vs}257 { color: ${Re.opaque(e.background).css}; }${this._terminalSelector} .${Vs}257.xterm-dim { color: ${Re.multiplyOpacity(Re.opaque(e.background),.5).css}; }${this._terminalSelector} .${nl}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Gi),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Gi),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,l=this._document.createDocumentFragment();if(i){let h=e[0]>t[0];l.appendChild(this._createSelectionElement(n,h?t[0]:e[0],h?e[0]:t[0],o-n+1))}else{let h=s===n?e[0]:0,a=n===r?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(n,h,a));let u=o-n-1;if(l.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,u)),n!==o){let d=r===o?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(o,0,d))}}this._selectionContainer.appendChild(l)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=`${s*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,l=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){let a=h+i.ydisp,u=this._rowElements[h],d=i.lines.get(a);if(!u||!d)break;u.replaceChildren(...this._rowFactory.createRow(d,a,a===s,o,l,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${hn}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let l=this._bufferService.buffer,h=l.ybase+l.y,a=Math.min(l.x,r-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,m=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=i;p<=s;++p){let _=p+l.ydisp,g=this._rowElements[p],y=l.lines.get(_);if(!g||!y)break;g.replaceChildren(...this._rowFactory.createRow(y,_,_===h,d,m,a,u,this.dimensions.css.cell.width,this._widthCache,n?p===i?e:0:-1,n?(p===s?t:r)-1:-1))}}};qn=He([K(7,no),K(8,fr),K(9,ut),K(10,dt),K(11,vi),K(12,Vt),K(13,Ai)],qn);var Vn=class extends he{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new N),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new cf(this._optionsService))}catch{this._measureStrategy=this._register(new hf(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Vn=He([K(2,ut)],Vn);var uh=class extends he{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},hf=class extends uh{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},cf=class extends uh{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},df=class extends he{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new uf(this._window)),this._onDprChange=this._register(new N),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new N),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(rt.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(ie(this._textarea,"focus",()=>this._isFocused=!0)),this._register(ie(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},uf=class extends he{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Li),this._onDprChange=this._register(new N),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Te(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=ie(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},ff=class extends he{constructor(){super(),this.linkProviders=[],this._register(Te(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function po(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}function pf(e,t,i,s,r,n,o,l,h){if(!n)return;let a=po(e,t,i);if(a)return a[0]=Math.ceil((a[0]+(h?o/2:0))/o),a[1]=Math.ceil(a[1]/l),a[0]=Math.min(Math.max(a[0],1),s+(h?1:0)),a[1]=Math.min(Math.max(a[1],1),r),a}var jn=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return pf(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=po(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};jn=He([K(0,jt),K(1,fr)],jn);var _f=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},fh={};ed(fh,{getSafariVersion:()=>gf,isChromeOS:()=>gh,isFirefox:()=>ph,isIpad:()=>vf,isIphone:()=>yf,isLegacyEdge:()=>mf,isLinux:()=>_o,isMac:()=>hr,isNode:()=>mr,isSafari:()=>_h,isWindows:()=>mh});var mr=typeof process<"u"&&"title"in process,ms=mr?"node":navigator.userAgent,gs=mr?"node":navigator.platform,ph=ms.includes("Firefox"),mf=ms.includes("Edge"),_h=/^((?!chrome|android).)*safari/i.test(ms);function gf(){if(!_h)return 0;let e=ms.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var hr=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(gs),vf=gs==="iPad",yf=gs==="iPhone",mh=["Windows","Win16","Win32","WinCE"].includes(gs),_o=gs.indexOf("Linux")>=0,gh=/\bCrOS\b/.test(ms),vh=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),i*1.5>r){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=r}this.clear()}},Sf=class extends vh{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},bf=class extends vh{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},cr=!mr&&"requestIdleCallback"in window?bf:Sf,wf=class{constructor(){this._queue=new cr}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Yn=class extends he{constructor(e,t,i,s,r,n,o,l,h){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=l,this._renderer=this._register(new Li),this._pausedResizeTask=new wf,this._observerDisposable=this._register(new Li),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new N),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new N),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new N),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new N),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new _f((a,u)=>this._renderRows(a,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Cf(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Te(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(h.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(a=>this._registerIntersectionObserver(a,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Te(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Yn=He([K(2,ut),K(3,fr),K(4,vi),K(5,_s),K(6,dt),K(7,Vt),K(8,Ai)],Yn);var Cf=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function xf(e,t,i,s){let r=i.buffer.x,n=i.buffer.y;if(!i.buffer.hasScrollback)return Rf(r,n,e,t,i,s)+gr(n,t,i,s)+Tf(r,n,e,t,i,s);let o;if(n===t)return o=r>e?"D":"C",us(Math.abs(r-e),ds(o,s));o=n>t?"D":"C";let l=Math.abs(n-t),h=Ef(n>t?e:r,i)+(l-1)*i.cols+1+kf(n>t?r:e,i);return us(h,ds(o,s))}function kf(e,t){return e-1}function Ef(e,t){return t.cols-e}function Rf(e,t,i,s,r,n){return gr(t,s,r,n).length===0?"":us(Sh(e,t,e,t-gi(t,r),!1,r).length,ds("D",n))}function gr(e,t,i,s){let r=e-gi(e,i),n=t-gi(t,i),o=Math.abs(r-n)-Df(e,t,i);return us(o,ds(yh(e,t),s))}function Tf(e,t,i,s,r,n){let o;gr(t,s,r,n).length>0?o=s-gi(s,r):o=t;let l=s,h=Bf(e,t,i,s,r,n);return us(Sh(e,o,i,l,h==="C",r).length,ds(h,n))}function Df(e,t,i){let s=0,r=e-gi(e,i),n=t-gi(t,i);for(let o=0;o<Math.abs(r-n);o++){let l=yh(e,t)==="A"?-1:1;i.buffer.lines.get(r+l*o)?.isWrapped&&s++}return s}function gi(e,t){let i=0,s=t.buffer.lines.get(e),r=s?.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=s?.isWrapped;return i}function Bf(e,t,i,s,r,n){let o;return gr(i,s,r,n).length>0?o=s-gi(s,r):o=t,e<i&&o<=s||e>=i&&o<s?"C":"D"}function yh(e,t){return e>t?"A":"B"}function Sh(e,t,i,s,r,n){let o=e,l=t,h="";for(;(o!==i||l!==s)&&l>=0&&l<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(l,!1,e,o),o=0,e=0,l++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(l,!1,0,e+1),o=n.cols-1,e=o,l--);return h+n.buffer.translateBufferLineToString(l,!1,e,o)}function ds(e,t){let i=t?"O":"[";return S.ESC+i+e}function us(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}var Lf=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function ol(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var cn=50,Af=15,Mf=50,Pf=500,If=" ",Of=new RegExp(If,"g"),Gn=class extends he{constructor(e,t,i,s,r,n,o,l,h){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=l,this._coreBrowserService=h,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Rt,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new N),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new N),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new N),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new N),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=a=>this._handleMouseMove(a),this._mouseUpListener=a=>this._handleMouseUp(a),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(a=>this._handleTrim(a)),this._register(this._bufferService.buffers.onBufferActivate(a=>this._handleBufferActivate(a))),this.enable(),this._model=new Lf(this._bufferService),this._activeSelectionMode=0,this._register(Te(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(a=>{a.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let l=i.translateBufferLineToString(o,!0,r,n);s.push(l)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let o=i.lines.get(n),l=i.translateBufferLineToString(n,!0);o?.isWrapped?s[s.length-1]+=l:s.push(l)}if(e[1]!==t[1]){let n=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);n&&n.isWrapped?s[s.length-1]+=o:s.push(o)}}return s.map(r=>r.replace(Of," ")).join(mh?`\r
|
|
50
|
+
`).trim(),c=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(l);gr.register(o,c?.[2]??l,o)}return o}),this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;let s=this._deliveryQueue.current===this;if(this._size*$d<=t.length){let r=0;for(let n=0;n<t.length;n++)t[n]?t[r++]=t[n]:s&&(this._deliveryQueue.end--,r<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=r}}_deliver(e,t){if(!e)return;let i=this._options?.onListenerError||_r;if(!i){e.value(t);return}try{e.value(t)}catch(s){i(s)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof mr)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},Ud=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Zn=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new N,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new N,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Zn.INSTANCE=new Zn;var Lo=Zn;function qd(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}var H_=Lo.INSTANCE.onDidChangeZoomLevel;function Vd(e){return Lo.INSTANCE.getZoomFactor(e)}var W_=Lo.INSTANCE.onDidChangeFullscreen,Ji=typeof navigator=="object"?navigator.userAgent:"",Qn=Ji.indexOf("Firefox")>=0,vr=Ji.indexOf("AppleWebKit")>=0,To=Ji.indexOf("Chrome")>=0,pc=!To&&Ji.indexOf("Safari")>=0,z_=Ji.indexOf("Electron/")>=0,$_=Ji.indexOf("Android")>=0,yr=!1;if(typeof At.matchMedia=="function"){let e=At.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=At.matchMedia("(display-mode: fullscreen)");yr=e.matches,qd(At,e,({matches:i})=>{yr&&t.matches||(yr=i)})}function jd(){return yr}var Yi="en",xr=!1,kr=!1,ks=!1,Yd=!1,_c=!1,mc=!1,Gd=!1,Xd=!1,Jd=!1,Zd=!1,hr,Sr=Yi,Qa=Yi,Qd,ti,si=globalThis,Dt;typeof si.vscode<"u"&&typeof si.vscode.process<"u"?Dt=si.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Dt=process);var gc=typeof Dt?.versions?.electron=="string",eu=gc&&Dt?.type==="renderer";if(typeof Dt=="object"){xr=Dt.platform==="win32",kr=Dt.platform==="darwin",ks=Dt.platform==="linux",Yd=ks&&!!Dt.env.SNAP&&!!Dt.env.SNAP_REVISION,Gd=gc,Jd=!!Dt.env.CI||!!Dt.env.BUILD_ARTIFACTSTAGINGDIRECTORY,hr=Yi,Sr=Yi;let e=Dt.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);hr=t.userLocale,Qa=t.osLocale,Sr=t.resolvedLanguage||Yi,Qd=t.languagePack?.translationsConfigFile}catch{}_c=!0}else typeof navigator=="object"&&!eu?(ti=navigator.userAgent,xr=ti.indexOf("Windows")>=0,kr=ti.indexOf("Macintosh")>=0,Xd=(ti.indexOf("Macintosh")>=0||ti.indexOf("iPad")>=0||ti.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ks=ti.indexOf("Linux")>=0,Zd=ti?.indexOf("Mobi")>=0,mc=!0,Sr=globalThis._VSCODE_NLS_LANGUAGE||Yi,hr=navigator.language.toLowerCase(),Qa=hr):console.error("Unable to resolve platform.");var wn=0;kr?wn=1:xr?wn=3:ks&&(wn=2);var vc=xr,Xt=kr,tu=ks,Cn=_c,iu=mc&&typeof si.importScripts=="function",K_=iu?si.origin:void 0,Jt=ti,di=Sr,el;(e=>{function t(){return di}e.value=t;function i(){return di.length===2?di==="en":di.length>=3?di[0]==="e"&&di[1]==="n"&&di[2]==="-":!1}e.isDefaultVariant=i;function s(){return di==="en"}e.isDefault=s})(el||(el={}));var su=typeof si.postMessage=="function"&&!si.importScripts,ru=(()=>{if(su){let e=[];si.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,r=e.length;s<r;s++){let n=e[s];if(n.id===i.data.vscodeScheduleAsyncWork){e.splice(s,1),n.callback();return}}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),si.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})(),nu=!!(Jt&&Jt.indexOf("Chrome")>=0),U_=!!(Jt&&Jt.indexOf("Firefox")>=0),q_=!!(!nu&&Jt&&Jt.indexOf("Safari")>=0),V_=!!(Jt&&Jt.indexOf("Edg/")>=0),j_=!!(Jt&&Jt.indexOf("Android")>=0),ui=typeof navigator=="object"?navigator:{},Y_={clipboard:{writeText:Cn||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(ui&&ui.clipboard&&ui.clipboard.writeText),readText:Cn||!!(ui&&ui.clipboard&&ui.clipboard.readText)},keyboard:Cn||jd()?0:ui.keyboard||pc?1:2,touch:"ontouchstart"in At||ui.maxTouchPoints>0,pointerEvents:At.PointerEvent&&("ontouchstart"in At||navigator.maxTouchPoints>0)},Do=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},xn=new Do,tl=new Do,il=new Do,ou=new Array(230),eo;(e=>{function t(l){return xn.keyCodeToStr(l)}e.toString=t;function i(l){return xn.strToKeyCode(l)}e.fromString=i;function s(l){return tl.keyCodeToStr(l)}e.toUserSettingsUS=s;function r(l){return il.keyCodeToStr(l)}e.toUserSettingsGeneral=r;function n(l){return tl.strToKeyCode(l)||il.strToKeyCode(l)}e.fromUserSettings=n;function o(l){if(l>=98&&l<=113)return null;switch(l){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return xn.keyCodeToStr(l)}e.toElectronAccelerator=o})(eo||(eo={}));var au=class yc{constructor(t,i,s,r,n){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=r,this.keyCode=n}equals(t){return t instanceof yc&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${i}${s}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new lu([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},lu=class{constructor(e){if(e.length===0)throw Sd("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;t++)t!==0&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function cu(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return eo.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Qn)switch(t){case 59:return 85;case 60:if(tu)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Xt)return 57;break}else if(vr&&(Xt&&t===93||!Xt&&t===92))return 57;return ou[t]||0}var hu=Xt?256:2048,du=512,uu=1024,fu=Xt?2048:256,to=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.("AltGraph"),this.keyCode=cu(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=hu),this.altKey&&(t|=du),this.shiftKey&&(t|=uu),this.metaKey&&(t|=fu),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new au(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},sl=new WeakMap;function pu(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var _u=class{static getSameOriginWindowChain(e){let t=sl.get(e);if(!t){t=[],sl.set(e,t);let i=e,s;do s=pu(i),s?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=s;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let o=n.window.deref();if(i+=o?.scrollY??0,s+=o?.scrollX??0,o===t||!n.iframeElement)break;let l=n.iframeElement.getBoundingClientRect();i+=l.top,s+=l.left}return{top:i,left:s}}},ys=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type==="dblclick"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX=="number"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=_u.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},rl=class{constructor(e,t=0,i=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let s=!1;if(To){let r=navigator.userAgent.match(/Chrome\/(\d+)/);s=(r?parseInt(r[1]):123)<=122}if(e){let r=e,n=e,o=e.view?.devicePixelRatio||1;if(typeof r.wheelDeltaY<"u")s?this.deltaY=r.wheelDeltaY/(120*o):this.deltaY=r.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<"u"&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type==="wheel"){let l=e;l.deltaMode===l.DOM_DELTA_LINE?Qn&&!Xt?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof r.wheelDeltaX<"u")pc&&vc?this.deltaX=-(r.wheelDeltaX/120):s?this.deltaX=r.wheelDeltaX/(120*o):this.deltaX=r.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<"u"&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let l=e;l.deltaMode===l.DOM_DELTA_LINE?Qn&&!Xt?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(s?this.deltaY=e.wheelDelta/(120*o):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Sc=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),nl;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof mu?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ht.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Sc})})(nl||(nl={}));var mu=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Sc:(this._emitter||(this._emitter=new N),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var Ao=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Kn("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Kn("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},gu=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Kn("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Be(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},vu,kn;(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?kn=(e,t)=>{ru(()=>{if(i)return;let s=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,s-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:kn=(e,t,i)=>{let s=e.requestIdleCallback(t,typeof i=="number"?{timeout:i}:void 0),r=!1;return{dispose(){r||(r=!0,e.cancelIdleCallback(s))}}},vu=e=>kn(globalThis,e)})();var ol;(e=>{async function t(s){let r,n=await Promise.all(s.map(o=>o.then(l=>l,l=>{r||(r=l)})));if(typeof r<"u")throw r;return n}e.settled=t;function i(s){return new Promise(async(r,n)=>{try{await s(r,n)}catch(o){n(o)}})}e.withAsyncBody=i})(ol||(ol={}));var al=class It{static fromArray(t){return new It(i=>{i.emitMany(t)})}static fromPromise(t){return new It(async i=>{i.emitMany(await t)})}static fromPromises(t){return new It(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new It(async i=>{await Promise.all(t.map(async s=>{for await(let r of s)i.emitOne(r)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new N,queueMicrotask(async()=>{let s={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(s)),this.resolve()}catch(r){this.reject(r)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await ht.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,i){return new It(async s=>{for await(let r of t)s.emitOne(i(r))})}map(t){return It.map(this,t)}static filter(t,i){return new It(async s=>{for await(let r of t)i(r)&&s.emitOne(r)})}filter(t){return It.filter(this,t)}static coalesce(t){return It.filter(t,i=>!!i)}coalesce(){return It.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return It.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};al.EMPTY=al.fromArray([]);function yu(e){return 55296<=e&&e<=56319}function ll(e){return 56320<=e&&e<=57343}function Su(e,t){return(e-55296<<10)+(t-56320)+65536}function bu(e){return Bo(e,0)}function Bo(e,t){switch(typeof e){case"object":return e===null?ii(349,t):Array.isArray(e)?Cu(e,t):xu(e,t);case"string":return bc(e,t);case"boolean":return wu(e,t);case"number":return ii(e,t);case"undefined":return ii(937,t);default:return ii(617,t)}}function ii(e,t){return(t<<5)-t+e|0}function wu(e,t){return ii(e?433:863,t)}function bc(e,t){t=ii(149417,t);for(let i=0,s=e.length;i<s;i++)t=ii(e.charCodeAt(i),t);return t}function Cu(e,t){return t=ii(104579,t),e.reduce((i,s)=>Bo(s,i),t)}function xu(e,t){return t=ii(181387,t),Object.keys(e).sort().reduce((i,s)=>(i=bc(s,i),Bo(e[s],i)),t)}function En(e,t,i=32){let s=i-t,r=~((1<<s)-1);return(e<<t|(r&e)>>>s)>>>0}function cl(e,t=0,i=e.byteLength,s=0){for(let r=0;r<i;r++)e[t+r]=s}function ku(e,t,i="0"){for(;e.length<t;)e=i+e;return e}function us(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(i=>i.toString(16).padStart(2,"0")).join(""):ku((e>>>0).toString(16),t/4)}var Eu=class wc{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let i=t.length;if(i===0)return;let s=this._buff,r=this._buffLen,n=this._leftoverHighSurrogate,o,l;for(n!==0?(o=n,l=-1,n=0):(o=t.charCodeAt(0),l=0);;){let c=o;if(yu(o))if(l+1<i){let a=t.charCodeAt(l+1);ll(a)?(l++,c=Su(o,a)):c=65533}else{n=o;break}else ll(o)&&(c=65533);if(r=this._push(s,r,c),l++,l<i)o=t.charCodeAt(l);else break}this._buffLen=r,this._leftoverHighSurrogate=n}_push(t,i,s){return s<128?t[i++]=s:s<2048?(t[i++]=192|(s&1984)>>>6,t[i++]=128|(s&63)>>>0):s<65536?(t[i++]=224|(s&61440)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0):(t[i++]=240|(s&1835008)>>>18,t[i++]=128|(s&258048)>>>12,t[i++]=128|(s&4032)>>>6,t[i++]=128|(s&63)>>>0),i>=64&&(this._step(),i-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),i}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),us(this._h0)+us(this._h1)+us(this._h2)+us(this._h3)+us(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,cl(this._buff,this._buffLen),this._buffLen>56&&(this._step(),cl(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=wc._bigBlock32,i=this._buffDV;for(let d=0;d<64;d+=4)t.setUint32(d,i.getUint32(d,!1),!1);for(let d=64;d<320;d+=4)t.setUint32(d,En(t.getUint32(d-12,!1)^t.getUint32(d-32,!1)^t.getUint32(d-56,!1)^t.getUint32(d-64,!1),1),!1);let s=this._h0,r=this._h1,n=this._h2,o=this._h3,l=this._h4,c,a,u;for(let d=0;d<80;d++)d<20?(c=r&n|~r&o,a=1518500249):d<40?(c=r^n^o,a=1859775393):d<60?(c=r&n|r&o|n&o,a=2400959708):(c=r^n^o,a=3395469782),u=En(s,5)+c+l+a+t.getUint32(d*4,!1)&4294967295,l=o,o=n,n=En(r,30),r=s,s=u;this._h0=this._h0+s&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+n&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+l&4294967295}};Eu._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:G_,getWindow:Ut,getDocument:X_,getWindows:J_,getWindowsCount:Z_,getWindowId:hl,getWindowById:Q_,hasWindow:em,onDidRegisterWindow:Ru,onWillUnregisterWindow:tm,onDidUnregisterWindow:im}=(function(){let e=new Map,t={window:At,disposables:new gi};e.set(At.vscodeWindowId,t);let i=new N,s=new N,r=new N;function n(o,l){return(typeof o=="number"?e.get(o):void 0)??(l?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(o){if(e.has(o.vscodeWindowId))return ve.None;let l=new gi,c={window:o,disposables:l.add(new gi)};return e.set(o.vscodeWindowId,c),l.add(Be(()=>{e.delete(o.vscodeWindowId),s.fire(o)})),l.add(oe(o,ot.BEFORE_UNLOAD,()=>{r.fire(o)})),i.fire(c),l},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){let l=o;if(l?.ownerDocument?.defaultView)return l.ownerDocument.defaultView.window;let c=o;return c?.view?c.view.window:At},getDocument(o){return Ut(o).document}}})(),Lu=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function oe(e,t,i,s){return new Lu(e,t,i,s)}function Tu(e,t){return function(i){return t(new ys(e,i))}}function Du(e){return function(t){return e(new to(t))}}var dl=function(e,t,i,s){let r=i;return t==="click"||t==="mousedown"||t==="contextmenu"?r=Tu(Ut(e),i):(t==="keydown"||t==="keypress"||t==="keyup")&&(r=Du(i)),oe(e,t,r,s)},Au,Er,Bu=class extends gu{constructor(e){super(),this.defaultTarget=e&&Ut(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Rn=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){_r(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,r=n=>{i.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),s.set(n,!0);o.length>0;)o.sort(Rn.sort),o.shift().execute();s.set(n,!1)};Er=(n,o,l=0)=>{let c=hl(n),a=new Rn(o,l),u=e.get(c);return u||(u=[],e.set(c,u)),u.push(a),i.get(c)||(i.set(c,!0),n.requestAnimationFrame(()=>r(c))),a},Au=(n,o,l)=>{let c=hl(n);if(s.get(c)){let a=new Rn(o,l),u=t.get(c);return u||(u=[],t.set(c,u)),u.push(a),a}else return Er(n,o,l)}})();var ul=class br{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new br(t,i):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof br?t:new br(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};ul.None=new ul(0,0);function Mu(e){let t=e.getBoundingClientRect(),i=Ut(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var sm=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let s=this.mutationObservers.get(e);s||(s=new Map,this.mutationObservers.set(e,s));let r=bu(i),n=s.get(r);if(n)n.users+=1;else{let o=new N,l=new MutationObserver(a=>o.fire(a));l.observe(e,i);let c=n={users:1,observer:l,onDidMutate:o.event};t.add(Be(()=>{c.users-=1,c.users===0&&(o.dispose(),l.disconnect(),s?.delete(r),s?.size===0&&this.mutationObservers.delete(e))})),s.set(r,n)}return n.onDidMutate}},ot={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:vr?"webkitAnimationStart":"animationstart",ANIMATION_END:vr?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:vr?"webkitAnimationIteration":"animationiteration"},Pu=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function Cc(e,t,i,...s){let r=Pu.exec(t);if(!r)throw new Error("Bad use of emmet");let n=r[1]||"div",o;return e!=="http://www.w3.org/1999/xhtml"?o=document.createElementNS(e,n):o=document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\./g," ").trim()),i&&Object.entries(i).forEach(([l,c])=>{typeof c>"u"||(/^on\w+$/.test(l)?o[l]=c:l==="selected"?c&&o.setAttribute(l,"true"):o.setAttribute(l,c))}),o.append(...s),o}function Iu(e,t,...i){return Cc("http://www.w3.org/1999/xhtml",e,t,...i)}Iu.SVG=function(e,t,...i){return Cc("http://www.w3.org/2000/svg",e,t,...i)};var Ou=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function wt(e){return typeof e=="number"?`${e}px`:e}function Es(e){return new Ou(e)}var xc=class{constructor(){this._hooks=new gi,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(Be(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=Ut(e)}this._hooks.add(oe(n,ot.POINTER_MOVE,o=>{if(o.buttons!==i){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(oe(n,ot.POINTER_UP,o=>this.stopMonitoring(!0)))}};function Nu(e,t,i){let s=null,r=null;if(typeof i.value=="function"?(s="value",r=i.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",r=i.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;i[s]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var Kt;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Kt||(Kt={}));var Ss=class vt extends ve{constructor(){super(),this.dispatched=!1,this.targets=new Xa,this.ignoreTargets=new Xa,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ht.runAndSubscribe(Ru,({window:t,disposables:i})=>{i.add(oe(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(oe(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(oe(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:At,disposables:this._store}))}static addTarget(t){if(!vt.isTouchDevice())return ve.None;vt.INSTANCE||(vt.INSTANCE=Ga(new vt));let i=vt.INSTANCE.targets.push(t);return Be(i)}static ignoreTarget(t){if(!vt.isTouchDevice())return ve.None;vt.INSTANCE||(vt.INSTANCE=Ga(new vt));let i=vt.INSTANCE.ignoreTargets.push(t);return Be(i)}static isTouchDevice(){return"ontouchstart"in At||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,r=t.targetTouches.length;s<r;s++){let n=t.targetTouches.item(s);this.activeTouches[n.identifier]={id:n.identifier,initialTarget:n.target,initialTimeStamp:i,initialPageX:n.pageX,initialPageY:n.pageY,rollingTimestamps:[i],rollingPageX:[n.pageX],rollingPageY:[n.pageY]};let o=this.newGestureEvent(Kt.Start,n.target);o.pageX=n.pageX,o.pageY=n.pageY,this.dispatchEvent(o)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let l=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(l.identifier))){console.warn("move of an UNKNOWN touch",l);continue}let c=this.activeTouches[l.identifier],a=Date.now()-c.initialTimeStamp;if(a<vt.HOLD_DELAY&&Math.abs(c.initialPageX-Lt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Lt(c.rollingPageY))<30){let u=this.newGestureEvent(Kt.Tap,c.initialTarget);u.pageX=Lt(c.rollingPageX),u.pageY=Lt(c.rollingPageY),this.dispatchEvent(u)}else if(a>=vt.HOLD_DELAY&&Math.abs(c.initialPageX-Lt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Lt(c.rollingPageY))<30){let u=this.newGestureEvent(Kt.Contextmenu,c.initialTarget);u.pageX=Lt(c.rollingPageX),u.pageY=Lt(c.rollingPageY),this.dispatchEvent(u)}else if(r===1){let u=Lt(c.rollingPageX),d=Lt(c.rollingPageY),_=Lt(c.rollingTimestamps)-c.rollingTimestamps[0],m=u-c.rollingPageX[0],p=d-c.rollingPageY[0],g=[...this.targets].filter(y=>c.initialTarget instanceof Node&&y.contains(c.initialTarget));this.inertia(t,g,s,Math.abs(m)/_,m>0?1:-1,u,Math.abs(p)/_,p>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(Kt.End,c.initialTarget)),delete this.activeTouches[l.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Kt.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>vt.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Kt.Change||t.type===Kt.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let r=0,n=t.initialTarget;for(;n&&n!==s;)r++,n=n.parentElement;i.push([r,s])}i.sort((s,r)=>s[0]-r[0]);for(let[s,r]of i)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,l,c,a){this.handle=Er(t,()=>{let u=Date.now(),d=u-s,_=0,m=0,p=!0;r+=vt.SCROLL_FRICTION*d,l+=vt.SCROLL_FRICTION*d,r>0&&(p=!1,_=n*r*d),l>0&&(p=!1,m=c*l*d);let g=this.newGestureEvent(Kt.Change);g.translationX=_,g.translationY=m,i.forEach(y=>y.dispatchEvent(g)),p||this.inertia(t,i,u,r,n,o+_,l,c,a+m)})}onTouchMove(t){let i=Date.now();for(let s=0,r=t.changedTouches.length;s<r;s++){let n=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(n.identifier))){console.warn("end of an UNKNOWN touch",n);continue}let o=this.activeTouches[n.identifier],l=this.newGestureEvent(Kt.Change,o.initialTarget);l.translationX=n.pageX-Lt(o.rollingPageX),l.translationY=n.pageY-Lt(o.rollingPageY),l.pageX=n.pageX,l.pageY=n.pageY,this.dispatchEvent(l),o.rollingPageX.length>3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};Ss.SCROLL_FRICTION=-.005,Ss.HOLD_DELAY=700,Ss.CLEAR_TAP_COUNT_TIME=400,ze([Nu],Ss,"isTouchDevice",1);var Fu=Ss,Mo=class extends ve{onclick(e,t){this._register(oe(e,ot.CLICK,i=>t(new ys(Ut(e),i))))}onmousedown(e,t){this._register(oe(e,ot.MOUSE_DOWN,i=>t(new ys(Ut(e),i))))}onmouseover(e,t){this._register(oe(e,ot.MOUSE_OVER,i=>t(new ys(Ut(e),i))))}onmouseleave(e,t){this._register(oe(e,ot.MOUSE_LEAVE,i=>t(new ys(Ut(e),i))))}onkeydown(e,t){this._register(oe(e,ot.KEY_DOWN,i=>t(new to(i))))}onkeyup(e,t){this._register(oe(e,ot.KEY_UP,i=>t(new to(i))))}oninput(e,t){this._register(oe(e,ot.INPUT,t))}onblur(e,t){this._register(oe(e,ot.BLUR,t))}onfocus(e,t){this._register(oe(e,ot.FOCUS,t))}onchange(e,t){this._register(oe(e,ot.CHANGE,t))}ignoreGesture(e){return Fu.ignoreTarget(e)}},fl=11,Hu=class extends Mo{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=fl+"px",this.domNode.style.height=fl+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new xc),this._register(dl(this.bgDomNode,ot.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(dl(this.domNode,ot.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Bu),this._pointerdownScheduleRepeatTimer=this._register(new Ao)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Ut(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Wu=class io{constructor(t,i,s,r,n,o,l){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,r=r|0,n=n|0,o=o|0,l=l|0),this.rawScrollLeft=r,this.rawScrollTop=l,i<0&&(i=0),r+i>s&&(r=s-i),r<0&&(r=0),n<0&&(n=0),l+n>o&&(l=o-n),l<0&&(l=0),this.width=i,this.scrollWidth=s,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=l}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new io(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new io(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,l=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:l,scrollTopChanged:c}}},zu=class extends ve{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Wu(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new _l(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=_l.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},pl=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Ln(e,t){let i=t-e;return function(s){return e+i*Uu(s)}}function $u(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}var _l=class so{constructor(t,i,s,r){this.from=t,this.to=i,this.duration=r,this.startTime=s,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,i,s){if(Math.abs(t-i)>2.5*s){let r,n;return t<i?(r=t+.75*s,n=i-.75*s):(r=t-.75*s,n=i+.75*s),$u(Ln(t,r),Ln(n,i),.33)}return Ln(t,i)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let i=(t-this.startTime)/this.duration;if(i<1){let s=this.scrollLeft(i),r=this.scrollTop(i);return new pl(s,r,!1)}return new pl(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return so.start(t,i,s)}static start(t,i,s){s=s+10;let r=Date.now()-10;return new so(t,i,r,s)}};function Ku(e){return Math.pow(e,3)}function Uu(e){return 1-Ku(1-e)}var qu=class extends ve{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Ao)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},Vu=140,kc=class extends Mo{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new qu(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new xc),this._shouldRender=!0,this.domNode=Es(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(oe(this.domNode.domNode,ot.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Hu(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Es(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(oe(this.slider.domNode,ot.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let r=Mu(this.domNode.domNode);t=e.pageX-r.left,i=e.pageY-r.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let n=this._sliderOrthogonalPointerPosition(r),o=Math.abs(n-i);if(vc&&o>Vu){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let l=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(l))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Ec=class ro{constructor(t,i,s,r,n,o){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ro(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,r,n){let o=Math.max(0,s-t),l=Math.max(0,o-2*i),c=r>0&&r>s;if(!c)return{computedAvailableSize:Math.round(o),computedIsNeeded:c,computedSliderSize:Math.round(l),computedSliderRatio:0,computedSliderPosition:0};let a=Math.round(Math.max(20,Math.floor(s*l/r))),u=(l-a)/(r-s),d=n*u;return{computedAvailableSize:Math.round(o),computedIsNeeded:c,computedSliderSize:Math.round(a),computedSliderRatio:u,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=ro._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},ju=class extends kc{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Ec(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Yu=class extends kc{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Ec(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Gu=500,ml=50,gl=!0,Xu=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},no=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,i=0,s=1,r=this._rear;do{let n=r===this._front?t:Math.pow(2,-s);if(t-=n,i+=this._memory[r].score*n,r===this._front)break;r=(this._capacity+r-1)%this._capacity,s++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(To){let i=Ut(t.browserEvent),s=Vd(i);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,s){let r=null,n=new Xu(t,i,s);this._front===-1&&this._rear===-1?(this._memory[0]=n,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=n),n.score=this._computeScore(n,r)}_computeScore(t,i){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(i.deltaX),l=Math.abs(i.deltaY),c=Math.max(Math.min(r,o),1),a=Math.max(Math.min(n,l),1),u=Math.max(r,o),d=Math.max(n,l);u%c===0&&d%a===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};no.INSTANCE=new no;var Ju=no,Zu=class extends Mo{constructor(e,t,i){super(),this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new N),this.onWillScroll=this._onWillScroll.event,this._options=ef(t),this._scrollable=i,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let s={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Yu(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new ju(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Es(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Es(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Es(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new Ao),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Pi(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Xt&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new rl(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Pi(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new rl(i))};this._mouseWheelToDispose.push(oe(this._listenOnDomNode,ot.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Ju.INSTANCE;gl&&t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,n=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&n+r===0?n=r=0:Math.abs(r)>=Math.abs(n)?n=0:r=0),this._options.flipAxes&&([r,n]=[n,r]);let o=!Xt&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||o)&&!n&&(n=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(n=n*this._options.fastScrollSensitivity,r=r*this._options.fastScrollSensitivity);let l=this._scrollable.getFutureScrollPosition(),c={};if(r){let a=ml*r,u=l.scrollTop-(a<0?Math.floor(a):Math.ceil(a));this._verticalScrollbar.writeScrollPosition(c,u)}if(n){let a=ml*n,u=l.scrollLeft-(a<0?Math.floor(a):Math.ceil(a));this._horizontalScrollbar.writeScrollPosition(c,u)}c=this._scrollable.validateScrollPosition(c),(l.scrollLeft!==c.scrollLeft||l.scrollTop!==c.scrollTop)&&(gl&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Gu)}},Qu=class extends Zu{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function ef(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Xt&&(t.className+=" mac"),t}var oo=class extends ve{constructor(e,t,i,s,r,n,o,l){super(),this._bufferService=i,this._optionsService=o,this._renderService=l,this._onRequestScrollLines=this._register(new N),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new zu({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:a=>Er(s.window,a)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Qu(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(a=>{this._scrollableElement.updateOptions({handleMouseWheel:!(a&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(ht.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Be(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Be(()=>this._styleElement.remove())),this._register(ht.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
|
|
51
|
+
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(a=>this._handleScroll(a)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};oo=ze([U(2,St),U(3,ri),U(4,ec),U(5,Xi),U(6,bt),U(7,ni)],oo);var ao=class extends ve{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(n=>this._removeDecoration(n))),this._register(Be(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};ao=ze([U(1,St),U(2,ri),U(3,Ps),U(4,ni)],ao);var tf=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Yt={full:0,left:0,center:0,right:0},fi={full:0,left:0,center:0,right:0},fs={full:0,left:0,center:0,right:0},Rr=class extends ve{constructor(e,t,i,s,r,n,o,l){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=l,this._colorZoneStore=new tf,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(Be(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);fi.full=this._canvas.width,fi.left=e,fi.center=t,fi.right=e,this._refreshDrawHeightConstants(),fs.full=1,fs.left=1,fs.center=1+fi.left,fs.right=1+fi.left+fi.center}_refreshDrawHeightConstants(){Yt.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);Yt.left=t,Yt.center=t,Yt.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Yt.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Yt.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Yt.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Yt.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(fs[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Yt[e.position||"full"]/2),fi[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Yt[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Rr=ze([U(2,St),U(3,Ps),U(4,ni),U(5,bt),U(6,Xi),U(7,ri)],Rr);var b;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=`
|
|
52
|
+
`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(b||(b={}));var Rs;(e=>(e.PAD="",e.HOP="",e.BPH="",e.NBH="",e.IND="",e.NEL="
",e.SSA="",e.ESA="",e.HTS="",e.HTJ="",e.VTS="",e.PLD="",e.PLU="",e.RI="",e.SS2="",e.SS3="",e.DCS="",e.PU1="",e.PU2="",e.STS="",e.CCH="",e.MW="",e.SPA="",e.EPA="",e.SOS="",e.SGCI="",e.SCI="",e.CSI="",e.ST="",e.OSC="",e.PM="",e.APC=""))(Rs||(Rs={}));var lo;(e=>e.ST=`${b.ESC}\\`)(lo||(lo={}));var co=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${b.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),i=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+"px",this._compositionView.style.top=s+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let n=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+"px",this._textarea.style.top=s+"px",this._textarea.style.width=Math.max(n.width,1)+"px",this._textarea.style.height=Math.max(n.height,1)+"px",this._textarea.style.lineHeight=n.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};co=ze([U(2,St),U(3,bt),U(4,Oi),U(5,ni)],co);var at=0,lt=0,ct=0,We=0,vl={css:"#00000000",rgba:0},Ye;(e=>{function t(r,n,o,l){return l!==void 0?`#${Ti(r)}${Ti(n)}${Ti(o)}${Ti(l)}`:`#${Ti(r)}${Ti(n)}${Ti(o)}`}e.toCss=t;function i(r,n,o,l=255){return(r<<24|n<<16|o<<8|l)>>>0}e.toRgba=i;function s(r,n,o,l){return{css:e.toCss(r,n,o,l),rgba:e.toRgba(r,n,o,l)}}e.toColor=s})(Ye||(Ye={}));var Ae;(e=>{function t(c,a){if(We=(a.rgba&255)/255,We===1)return{css:a.css,rgba:a.rgba};let u=a.rgba>>24&255,d=a.rgba>>16&255,_=a.rgba>>8&255,m=c.rgba>>24&255,p=c.rgba>>16&255,g=c.rgba>>8&255;at=m+Math.round((u-m)*We),lt=p+Math.round((d-p)*We),ct=g+Math.round((_-g)*We);let y=Ye.toCss(at,lt,ct),x=Ye.toRgba(at,lt,ct);return{css:y,rgba:x}}e.blend=t;function i(c){return(c.rgba&255)===255}e.isOpaque=i;function s(c,a,u){let d=Ls.ensureContrastRatio(c.rgba,a.rgba,u);if(d)return Ye.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=s;function r(c){let a=(c.rgba|255)>>>0;return[at,lt,ct]=Ls.toChannels(a),{css:Ye.toCss(at,lt,ct),rgba:a}}e.opaque=r;function n(c,a){return We=Math.round(a*255),[at,lt,ct]=Ls.toChannels(c.rgba),{css:Ye.toCss(at,lt,ct,We),rgba:Ye.toRgba(at,lt,ct,We)}}e.opacity=n;function o(c,a){return We=c.rgba&255,n(c,We*a/255)}e.multiplyOpacity=o;function l(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=l})(Ae||(Ae={}));var Pe;(e=>{let t,i;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return at=parseInt(r.slice(1,2).repeat(2),16),lt=parseInt(r.slice(2,3).repeat(2),16),ct=parseInt(r.slice(3,4).repeat(2),16),Ye.toColor(at,lt,ct);case 5:return at=parseInt(r.slice(1,2).repeat(2),16),lt=parseInt(r.slice(2,3).repeat(2),16),ct=parseInt(r.slice(3,4).repeat(2),16),We=parseInt(r.slice(4,5).repeat(2),16),Ye.toColor(at,lt,ct,We);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return at=parseInt(n[1]),lt=parseInt(n[2]),ct=parseInt(n[3]),We=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),Ye.toColor(at,lt,ct,We);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=r,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[at,lt,ct,We]=t.getImageData(0,0,1,1).data,We!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ye.toRgba(at,lt,ct,We),css:r}}e.toColor=s})(Pe||(Pe={}));var yt;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,r,n){let o=s/255,l=r/255,c=n/255,a=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return a*.2126+u*.7152+d*.0722}e.relativeLuminance2=i})(yt||(yt={}));var Ls;(e=>{function t(o,l){if(We=(l&255)/255,We===1)return l;let c=l>>24&255,a=l>>16&255,u=l>>8&255,d=o>>24&255,_=o>>16&255,m=o>>8&255;return at=d+Math.round((c-d)*We),lt=_+Math.round((a-_)*We),ct=m+Math.round((u-m)*We),Ye.toRgba(at,lt,ct)}e.blend=t;function i(o,l,c){let a=yt.relativeLuminance(o>>8),u=yt.relativeLuminance(l>>8);if(ei(a,u)<c){if(u<a){let m=s(o,l,c),p=ei(a,yt.relativeLuminance(m>>8));if(p<c){let g=r(o,l,c),y=ei(a,yt.relativeLuminance(g>>8));return p>y?m:g}return m}let d=r(o,l,c),_=ei(a,yt.relativeLuminance(d>>8));if(_<c){let m=s(o,l,c),p=ei(a,yt.relativeLuminance(m>>8));return _>p?d:m}return d}}e.ensureContrastRatio=i;function s(o,l,c){let a=o>>24&255,u=o>>16&255,d=o>>8&255,_=l>>24&255,m=l>>16&255,p=l>>8&255,g=ei(yt.relativeLuminance2(_,m,p),yt.relativeLuminance2(a,u,d));for(;g<c&&(_>0||m>0||p>0);)_-=Math.max(0,Math.ceil(_*.1)),m-=Math.max(0,Math.ceil(m*.1)),p-=Math.max(0,Math.ceil(p*.1)),g=ei(yt.relativeLuminance2(_,m,p),yt.relativeLuminance2(a,u,d));return(_<<24|m<<16|p<<8|255)>>>0}e.reduceLuminance=s;function r(o,l,c){let a=o>>24&255,u=o>>16&255,d=o>>8&255,_=l>>24&255,m=l>>16&255,p=l>>8&255,g=ei(yt.relativeLuminance2(_,m,p),yt.relativeLuminance2(a,u,d));for(;g<c&&(_<255||m<255||p<255);)_=Math.min(255,_+Math.ceil((255-_)*.1)),m=Math.min(255,m+Math.ceil((255-m)*.1)),p=Math.min(255,p+Math.ceil((255-p)*.1)),g=ei(yt.relativeLuminance2(_,m,p),yt.relativeLuminance2(a,u,d));return(_<<24|m<<16|p<<8|255)>>>0}e.increaseLuminance=r;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(Ls||(Ls={}));function Ti(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ei(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var sf=class extends Ms{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Lr=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Nt}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let i=[],s=t.translateToString(!0),r=0,n=0,o=0,l=t.getFg(0),c=t.getBg(0);for(let a=0;a<t.getTrimmedLength();a++)if(t.loadCell(a,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==l||this._workCell.bg!==c){if(a-r>1){let u=this._getJoinedRanges(s,o,n,t,r);for(let d=0;d<u.length;d++)i.push(u[d])}r=a,o=n,l=this._workCell.fg,c=this._workCell.bg}n+=this._workCell.getChars().length||mi.length}if(this._bufferService.cols-r>1){let a=this._getJoinedRanges(s,o,n,t,r);for(let u=0;u<a.length;u++)i.push(a[u])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(l){console.error(l)}for(let l=1;l<this._characterJoiners.length;l++)try{let c=this._characterJoiners[l].handler(n);for(let a=0;a<c.length;a++)Lr._mergeRanges(o,c[a])}catch(c){console.error(c)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let l=i;l<this._bufferService.cols;l++){let c=t.getWidth(l),a=t.getString(l).length||mi.length;if(c!==0){if(!r&&o[0]<=n&&(o[0]=l,r=!0),o[1]<=n){if(o[1]=l,o=e[++s],!o)break;o[0]<=n?(o[0]=l,r=!0):r=!1}n+=a}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};Lr=ze([U(0,St)],Lr);function rf(e){return 57508<=e&&e<=57558}function nf(e){return 9472<=e&&e<=9631}function of(e){return rf(e)||nf(e)}function af(){return{css:{canvas:dr(),cell:dr()},device:{canvas:dr(),cell:dr(),char:{width:0,height:0,left:0,top:0}}}}function dr(){return{width:0,height:0}}var ho=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new Nt,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,l,c,a,u){let d=[],_=this._characterJoinerService.getJoinedCharacters(t),m=this._themeService.colors,p=e.getNoBgTrimmedLength();i&&p<n+1&&(p=n+1);let g,y=0,x="",q=0,W=0,k=0,M=0,Z=!1,K=0,ye=!1,ce=0,he=0,G=[],ke=a!==-1&&u!==-1;for(let R=0;R<p;R++){e.loadCell(R,this._workCell);let E=this._workCell.getWidth();if(E===0)continue;let B=!1,A=R>=he,T=R,w=this._workCell;if(_.length>0&&R===_[0][0]&&A){let ie=_.shift(),Bt=this._isCellInSelection(ie[0],t);for(q=ie[0]+1;q<ie[1];q++)A&&(A=Bt===this._isCellInSelection(q,t));A&&(A=!i||n<ie[0]||n>=ie[1]),A?(B=!0,w=new sf(this._workCell,e.translateToString(!0,ie[0],ie[1]),ie[1]-ie[0]),T=ie[1]-1,E=w.getWidth()):he=ie[1]}let I=this._isCellInSelection(R,t),P=i&&R===n,re=ke&&R>=a&&R<=u,Re=!1;this._decorationService.forEachDecorationAtCell(R,t,void 0,ie=>{Re=!0});let ee=w.getChars()||mi;if(ee===" "&&(w.isUnderline()||w.isOverline())&&(ee=" "),ce=E*l-c.get(ee,w.isBold(),w.isItalic()),!g)g=this._document.createElement("span");else if(y&&(I&&ye||!I&&!ye&&w.bg===W)&&(I&&ye&&m.selectionForeground||w.fg===k)&&w.extended.ext===M&&re===Z&&ce===K&&!P&&!B&&!Re&&A){w.isInvisible()?x+=mi:x+=ee,y++;continue}else y&&(g.textContent=x),g=this._document.createElement("span"),y=0,x="";if(W=w.bg,k=w.fg,M=w.extended.ext,Z=re,K=ce,ye=I,B&&n>=R&&n<=T&&(n=R),!this._coreService.isCursorHidden&&P&&this._coreService.isCursorInitialized){if(G.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&G.push("xterm-cursor-blink"),G.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":G.push("xterm-cursor-outline");break;case"block":G.push("xterm-cursor-block");break;case"bar":G.push("xterm-cursor-bar");break;case"underline":G.push("xterm-cursor-underline");break;default:break}}if(w.isBold()&&G.push("xterm-bold"),w.isItalic()&&G.push("xterm-italic"),w.isDim()&&G.push("xterm-dim"),w.isInvisible()?x=mi:x=w.getChars()||mi,w.isUnderline()&&(G.push(`xterm-underline-${w.extended.underlineStyle}`),x===" "&&(x=" "),!w.isUnderlineColorDefault()))if(w.isUnderlineColorRGB())g.style.textDecorationColor=`rgb(${Ms.toColorRGB(w.getUnderlineColor()).join(",")})`;else{let ie=w.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&w.isBold()&&ie<8&&(ie+=8),g.style.textDecorationColor=m.ansi[ie].css}w.isOverline()&&(G.push("xterm-overline"),x===" "&&(x=" ")),w.isStrikethrough()&&G.push("xterm-strikethrough"),re&&(g.style.textDecoration="underline");let fe=w.getFgColor(),Ge=w.getFgColorMode(),le=w.getBgColor(),O=w.getBgColorMode(),X=!!w.isInverse();if(X){let ie=fe;fe=le,le=ie;let Bt=Ge;Ge=O,O=Bt}let ae,kt,Ke=!1;this._decorationService.forEachDecorationAtCell(R,t,void 0,ie=>{ie.options.layer!=="top"&&Ke||(ie.backgroundColorRGB&&(O=50331648,le=ie.backgroundColorRGB.rgba>>8&16777215,ae=ie.backgroundColorRGB),ie.foregroundColorRGB&&(Ge=50331648,fe=ie.foregroundColorRGB.rgba>>8&16777215,kt=ie.foregroundColorRGB),Ke=ie.options.layer==="top")}),!Ke&&I&&(ae=this._coreBrowserService.isFocused?m.selectionBackgroundOpaque:m.selectionInactiveBackgroundOpaque,le=ae.rgba>>8&16777215,O=50331648,Ke=!0,m.selectionForeground&&(Ge=50331648,fe=m.selectionForeground.rgba>>8&16777215,kt=m.selectionForeground)),Ke&&G.push("xterm-decoration-top");let ut;switch(O){case 16777216:case 33554432:ut=m.ansi[le],G.push(`xterm-bg-${le}`);break;case 50331648:ut=Ye.toColor(le>>16,le>>8&255,le&255),this._addStyle(g,`background-color:#${yl((le>>>0).toString(16),"0",6)}`);break;default:X?(ut=m.foreground,G.push("xterm-bg-257")):ut=m.background}switch(ae||w.isDim()&&(ae=Ae.multiplyOpacity(ut,.5)),Ge){case 16777216:case 33554432:w.isBold()&&fe<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(fe+=8),this._applyMinimumContrast(g,ut,m.ansi[fe],w,ae,void 0)||G.push(`xterm-fg-${fe}`);break;case 50331648:let ie=Ye.toColor(fe>>16&255,fe>>8&255,fe&255);this._applyMinimumContrast(g,ut,ie,w,ae,kt)||this._addStyle(g,`color:#${yl(fe.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(g,ut,m.foreground,w,ae,kt)||X&&G.push("xterm-fg-257")}G.length&&(g.className=G.join(" "),G.length=0),!P&&!B&&!Re&&A?y++:g.textContent=x,ce!==this.defaultSpacing&&(g.style.letterSpacing=`${ce}px`),d.push(g),R=T}return g&&y&&(g.textContent=x),d}_applyMinimumContrast(e,t,i,s,r,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||of(s.getCode()))return!1;let o=this._getContrastCache(s),l;if(!r&&!n&&(l=o.getColor(t.rgba,i.rgba)),l===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);l=Ae.ensureContrastRatio(r||t,n||i,c),o.setColor((r||t).rgba,(n||i).rgba,l??null)}return l?(this._addStyle(e,`color:${l.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0]}};ho=ze([U(1,sc),U(2,bt),U(3,ri),U(4,Oi),U(5,Ps),U(6,Xi)],ho);function yl(e,t,i){for(;e.length<i;)e=t+e;return e}var lf=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&e.length===1&&(s=e.charCodeAt(0))<256){if(this._flat[s]!==-9999)return this._flat[s];let o=this._measure(e,0);return o>0&&(this._flat[s]=o),o}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(n===void 0){let o=0;t&&(o|=1),i&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},cf=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,l=Math.max(n,0),c=Math.min(o,e.rows-1);if(l>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=l,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function hf(){return new cf}var Tn="xterm-dom-renderer-owner-",Pt="xterm-rows",ur="xterm-fg-",Sl="xterm-bg-",ps="xterm-focus",fr="xterm-selection",df=1,uo=class extends ve{constructor(e,t,i,s,r,n,o,l,c,a,u,d,_,m){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=c,this._optionsService=a,this._bufferService=u,this._coreService=d,this._coreBrowserService=_,this._themeService=m,this._terminalClass=df++,this._rowElements=[],this._selectionRenderModel=hf(),this.onRequestRedraw=this._register(new N).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Pt),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(fr),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=af(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(p=>this._injectCss(p))),this._injectCss(this._themeService.colors),this._rowFactory=l.createInstance(ho,document),this._element.classList.add(Tn+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(p=>this._handleLinkHover(p))),this._register(this._linkifier2.onHideLinkUnderline(p=>this._handleLinkLeave(p))),this._register(Be(()=>{this._element.classList.remove(Tn+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new lf(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Pt} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Pt} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Pt} .xterm-dim { color: ${Ae.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Pt}.${ps} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Pt}.${ps} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Pt}.${ps} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Pt} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Pt} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Pt} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Pt} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Pt} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${fr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${fr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${fr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${ur}${n} { color: ${o.css}; }${this._terminalSelector} .${ur}${n}.xterm-dim { color: ${Ae.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${Sl}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${ur}257 { color: ${Ae.opaque(e.background).css}; }${this._terminalSelector} .${ur}257.xterm-dim { color: ${Ae.multiplyOpacity(Ae.opaque(e.background),.5).css}; }${this._terminalSelector} .${Sl}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ps),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ps),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,l=this._document.createDocumentFragment();if(i){let c=e[0]>t[0];l.appendChild(this._createSelectionElement(n,c?t[0]:e[0],c?e[0]:t[0],o-n+1))}else{let c=s===n?e[0]:0,a=n===r?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(n,c,a));let u=o-n-1;if(l.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,u)),n!==o){let d=r===o?t[0]:this._bufferService.cols;l.appendChild(this._createSelectionElement(o,0,d))}}this._selectionContainer.appendChild(l)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=`${s*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,l=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let a=c+i.ydisp,u=this._rowElements[c],d=i.lines.get(a);if(!u||!d)break;u.replaceChildren(...this._rowFactory.createRow(d,a,a===s,o,l,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Tn}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let l=this._bufferService.buffer,c=l.ybase+l.y,a=Math.min(l.x,r-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,_=this._optionsService.rawOptions.cursorInactiveStyle;for(let m=i;m<=s;++m){let p=m+l.ydisp,g=this._rowElements[m],y=l.lines.get(p);if(!g||!y)break;g.replaceChildren(...this._rowFactory.createRow(y,p,p===c,d,_,a,u,this.dimensions.css.cell.width,this._widthCache,n?m===i?e:0:-1,n?(m===s?t:r)-1:-1))}}};uo=ze([U(7,Eo),U(8,Mr),U(9,bt),U(10,St),U(11,Oi),U(12,ri),U(13,Xi)],uo);var fo=class extends ve{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new N),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new ff(this._optionsService))}catch{this._measureStrategy=this._register(new uf(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};fo=ze([U(2,bt)],fo);var Rc=class extends ve{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},uf=class extends Rc{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},ff=class extends Rc{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},pf=class extends ve{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new _f(this._window)),this._onDprChange=this._register(new N),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new N),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(ht.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(oe(this._textarea,"focus",()=>this._isFocused=!0)),this._register(oe(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},_f=class extends ve{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Gi),this._onDprChange=this._register(new N),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Be(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=oe(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},mf=class extends ve{constructor(){super(),this.linkProviders=[],this._register(Be(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Po(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}function gf(e,t,i,s,r,n,o,l,c){if(!n)return;let a=Po(e,t,i);if(a)return a[0]=Math.ceil((a[0]+(c?o/2:0))/o),a[1]=Math.ceil(a[1]/l),a[0]=Math.min(Math.max(a[0],1),s+(c?1:0)),a[1]=Math.min(Math.max(a[1],1),r),a}var po=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return gf(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=Po(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};po=ze([U(0,ni),U(1,Mr)],po);var vf=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Lc={};sd(Lc,{getSafariVersion:()=>Sf,isChromeOS:()=>Bc,isFirefox:()=>Tc,isIpad:()=>bf,isIphone:()=>wf,isLegacyEdge:()=>yf,isLinux:()=>Io,isMac:()=>Tr,isNode:()=>Or,isSafari:()=>Dc,isWindows:()=>Ac});var Or=typeof process<"u"&&"title"in process,Is=Or?"node":navigator.userAgent,Os=Or?"node":navigator.platform,Tc=Is.includes("Firefox"),yf=Is.includes("Edge"),Dc=/^((?!chrome|android).)*safari/i.test(Is);function Sf(){if(!Dc)return 0;let e=Is.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Tr=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Os),bf=Os==="iPad",wf=Os==="iPhone",Ac=["Windows","Win16","Win32","WinCE"].includes(Os),Io=Os.indexOf("Linux")>=0,Bc=/\bCrOS\b/.test(Is),Mc=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),i*1.5>r){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=r}this.clear()}},Cf=class extends Mc{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},xf=class extends Mc{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Dr=!Or&&"requestIdleCallback"in window?xf:Cf,kf=class{constructor(){this._queue=new Dr}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},_o=class extends ve{constructor(e,t,i,s,r,n,o,l,c){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=l,this._renderer=this._register(new Gi),this._pausedResizeTask=new kf,this._observerDisposable=this._register(new Gi),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new N),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new N),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new N),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new N),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new vf((a,u)=>this._renderRows(a,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Ef(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Be(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(a=>this._registerIntersectionObserver(a,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Be(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};_o=ze([U(2,bt),U(3,Mr),U(4,Oi),U(5,Ps),U(6,St),U(7,ri),U(8,Xi)],_o);var Ef=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Rf(e,t,i,s){let r=i.buffer.x,n=i.buffer.y;if(!i.buffer.hasScrollback)return Df(r,n,e,t,i,s)+Nr(n,t,i,s)+Af(r,n,e,t,i,s);let o;if(n===t)return o=r>e?"D":"C",As(Math.abs(r-e),Ds(o,s));o=n>t?"D":"C";let l=Math.abs(n-t),c=Tf(n>t?e:r,i)+(l-1)*i.cols+1+Lf(n>t?r:e,i);return As(c,Ds(o,s))}function Lf(e,t){return e-1}function Tf(e,t){return t.cols-e}function Df(e,t,i,s,r,n){return Nr(t,s,r,n).length===0?"":As(Ic(e,t,e,t-Ii(t,r),!1,r).length,Ds("D",n))}function Nr(e,t,i,s){let r=e-Ii(e,i),n=t-Ii(t,i),o=Math.abs(r-n)-Bf(e,t,i);return As(o,Ds(Pc(e,t),s))}function Af(e,t,i,s,r,n){let o;Nr(t,s,r,n).length>0?o=s-Ii(s,r):o=t;let l=s,c=Mf(e,t,i,s,r,n);return As(Ic(e,o,i,l,c==="C",r).length,Ds(c,n))}function Bf(e,t,i){let s=0,r=e-Ii(e,i),n=t-Ii(t,i);for(let o=0;o<Math.abs(r-n);o++){let l=Pc(e,t)==="A"?-1:1;i.buffer.lines.get(r+l*o)?.isWrapped&&s++}return s}function Ii(e,t){let i=0,s=t.buffer.lines.get(e),r=s?.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=s?.isWrapped;return i}function Mf(e,t,i,s,r,n){let o;return Nr(i,s,r,n).length>0?o=s-Ii(s,r):o=t,e<i&&o<=s||e>=i&&o<s?"C":"D"}function Pc(e,t){return e>t?"A":"B"}function Ic(e,t,i,s,r,n){let o=e,l=t,c="";for(;(o!==i||l!==s)&&l>=0&&l<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(c+=n.buffer.translateBufferLineToString(l,!1,e,o),o=0,e=0,l++):!r&&o<0&&(c+=n.buffer.translateBufferLineToString(l,!1,0,e+1),o=n.cols-1,e=o,l--);return c+n.buffer.translateBufferLineToString(l,!1,e,o)}function Ds(e,t){let i=t?"O":"[";return b.ESC+i+e}function As(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}var Pf=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function bl(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Dn=50,If=15,Of=50,Nf=500,Ff=" ",Hf=new RegExp(Ff,"g"),mo=class extends ve{constructor(e,t,i,s,r,n,o,l,c){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=l,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Nt,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new N),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new N),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new N),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new N),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=a=>this._handleMouseMove(a),this._mouseUpListener=a=>this._handleMouseUp(a),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(a=>this._handleTrim(a)),this._register(this._bufferService.buffers.onBufferActivate(a=>this._handleBufferActivate(a))),this.enable(),this._model=new Pf(this._bufferService),this._activeSelectionMode=0,this._register(Be(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(a=>{a.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let l=i.translateBufferLineToString(o,!0,r,n);s.push(l)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let o=i.lines.get(n),l=i.translateBufferLineToString(n,!0);o?.isWrapped?s[s.length-1]+=l:s.push(l)}if(e[1]!==t[1]){let n=i.lines.get(t[1]),o=i.translateBufferLineToString(t[1],!0,0,t[0]);n&&n.isWrapped?s[s.length-1]+=o:s.push(o)}}return s.map(r=>r.replace(Hf," ")).join(Ac?`\r
|
|
53
53
|
`:`
|
|
54
|
-
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),_o&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=ol(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=po(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-cn),cn),t/=cn,t/Math.abs(t)+Math.round(t*(Af-1)))}shouldForceSelection(e){return hr?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Mf)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(hr&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let s=i.lines.get(this._model.selectionEnd[1]);s&&s.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Pf&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let s=xf(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(s,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),l=this._convertViewportColToCharacterIndex(n,e[0]),h=l,a=e[0]-l,u=0,d=0,m=0,p=0;if(o.charAt(l)===" "){for(;l>0&&o.charAt(l-1)===" ";)l--;for(;h<o.length&&o.charAt(h+1)===" ";)h++}else{let y=e[0],x=e[0];n.getWidth(y)===0&&(u++,y--),n.getWidth(x)===2&&(d++,x++);let j=n.getString(x).length;for(j>1&&(p+=j-1,h+=j-1);y>0&&l>0&&!this._isCharWordSeparator(n.loadCell(y-1,this._workCell));){n.loadCell(y-1,this._workCell);let z=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,y--):z>1&&(m+=z-1,l-=z-1),l--,y--}for(;x<n.length&&h+1<o.length&&!this._isCharWordSeparator(n.loadCell(x+1,this._workCell));){n.loadCell(x+1,this._workCell);let z=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,x++):z>1&&(p+=z-1,h+=z-1),h++,x++}}h++;let _=l+a-u+m,g=Math.min(this._bufferService.cols,h-l+u+d-m-p);if(!(!t&&o.slice(l,h).trim()==="")){if(i&&_===0&&n.getCodePoint(0)!==32){let y=r.lines.get(e[1]-1);if(y&&n.isWrapped&&y.getCodePoint(this._bufferService.cols-1)!==32){let x=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(x){let j=this._bufferService.cols-x.start;_-=j,g+=j}}}if(s&&_+g===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let y=r.lines.get(e[1]+1);if(y?.isWrapped&&y.getCodePoint(0)!==32){let x=this._getWordAt([0,e[1]+1],!1,!1,!0);x&&(g+=x.length)}}return{start:_,length:g}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=ol(i,this._bufferService.cols)}};Gn=He([K(3,dt),K(4,vi),K(5,oo),K(6,ut),K(7,jt),K(8,Vt)],Gn);var al=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},ll=class{constructor(){this._color=new al,this._css=new al}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ge=Object.freeze((()=>{let e=[Be.toColor("#2e3436"),Be.toColor("#cc0000"),Be.toColor("#4e9a06"),Be.toColor("#c4a000"),Be.toColor("#3465a4"),Be.toColor("#75507b"),Be.toColor("#06989a"),Be.toColor("#d3d7cf"),Be.toColor("#555753"),Be.toColor("#ef2929"),Be.toColor("#8ae234"),Be.toColor("#fce94f"),Be.toColor("#729fcf"),Be.toColor("#ad7fa8"),Be.toColor("#34e2e2"),Be.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:Ke.toCss(s,r,n),rgba:Ke.toRgba(s,r,n)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ke.toCss(s,s,s),rgba:Ke.toRgba(s,s,s)})}return e})()),ui=Be.toColor("#ffffff"),is=Be.toColor("#000000"),hl=Be.toColor("#ffffff"),cl=is,Xi={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Nf=ui,Xn=class extends he{constructor(e){super(),this._optionsService=e,this._contrastCache=new ll,this._halfContrastCache=new ll,this._onChangeColors=this._register(new N),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ui,background:is,cursor:hl,cursorAccent:cl,selectionForeground:void 0,selectionBackgroundTransparent:Xi,selectionBackgroundOpaque:Re.blend(is,Xi),selectionInactiveBackgroundTransparent:Xi,selectionInactiveBackgroundOpaque:Re.blend(is,Xi),scrollbarSliderBackground:Re.opacity(ui,.2),scrollbarSliderHoverBackground:Re.opacity(ui,.4),scrollbarSliderActiveBackground:Re.opacity(ui,.5),overviewRulerBorder:ui,ansi:Ge.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=xe(e.foreground,ui),t.background=xe(e.background,is),t.cursor=Re.blend(t.background,xe(e.cursor,hl)),t.cursorAccent=Re.blend(t.background,xe(e.cursorAccent,cl)),t.selectionBackgroundTransparent=xe(e.selectionBackground,Xi),t.selectionBackgroundOpaque=Re.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=xe(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Re.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?xe(e.selectionForeground,sl):void 0,t.selectionForeground===sl&&(t.selectionForeground=void 0),Re.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Re.opacity(t.selectionBackgroundTransparent,.3)),Re.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Re.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=xe(e.scrollbarSliderBackground,Re.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=xe(e.scrollbarSliderHoverBackground,Re.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=xe(e.scrollbarSliderActiveBackground,Re.opacity(t.foreground,.5)),t.overviewRulerBorder=xe(e.overviewRulerBorder,Nf),t.ansi=Ge.slice(),t.ansi[0]=xe(e.black,Ge[0]),t.ansi[1]=xe(e.red,Ge[1]),t.ansi[2]=xe(e.green,Ge[2]),t.ansi[3]=xe(e.yellow,Ge[3]),t.ansi[4]=xe(e.blue,Ge[4]),t.ansi[5]=xe(e.magenta,Ge[5]),t.ansi[6]=xe(e.cyan,Ge[6]),t.ansi[7]=xe(e.white,Ge[7]),t.ansi[8]=xe(e.brightBlack,Ge[8]),t.ansi[9]=xe(e.brightRed,Ge[9]),t.ansi[10]=xe(e.brightGreen,Ge[10]),t.ansi[11]=xe(e.brightYellow,Ge[11]),t.ansi[12]=xe(e.brightBlue,Ge[12]),t.ansi[13]=xe(e.brightMagenta,Ge[13]),t.ansi[14]=xe(e.brightCyan,Ge[14]),t.ansi[15]=xe(e.brightWhite,Ge[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=xe(e.extendedAnsi[s],Ge[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};Xn=He([K(0,ut)],Xn);function xe(e,t){if(e!==void 0)try{return Be.toColor(e)}catch{}return t}var Ff=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Hf=class{constructor(){this._services=new Ff,this._services.set(no,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=ad(e).sort((n,o)=>n.index-o.index),s=[];for(let n of i){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);s.push(o)}let r=i.length>0?i[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},Wf={trace:0,debug:1,info:2,warn:3,error:4,off:5},zf="xterm.js: ",Jn=class extends he{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),$f=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Wf[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":zf)+t,...i)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};Jn=He([K(0,ut)],Jn);var $f,dl=class extends he{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new N),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new N),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new N),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let s=e;s<this._length-t;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},ue=3,je=Object.freeze(new ps),Ys=0,dn=2,ss=class bh{constructor(t,i,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*ue);let r=i||Rt.fromCharData([0,Il,1,0]);for(let n=0;n<t;++n)this.setCell(n,r);this.length=t}get(t){let i=this._data[t*ue+0],s=i&2097151;return[this._data[t*ue+1],i&2097152?this._combined[t]:s?ti(s):"",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*ue+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ue+0]=t|2097152|i[2]<<22):this._data[t*ue+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ue+0]>>22}hasWidth(t){return this._data[t*ue+0]&12582912}getFg(t){return this._data[t*ue+1]}getBg(t){return this._data[t*ue+2]}hasContent(t){return this._data[t*ue+0]&4194303}getCodePoint(t){let i=this._data[t*ue+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ue+0]&2097152}getString(t){let i=this._data[t*ue+0];return i&2097152?this._combined[t]:i&2097151?ti(i&2097151):""}isProtected(t){return this._data[t*ue+2]&536870912}loadCell(t,i){return Ys=t*ue,i.content=this._data[Ys+0],i.fg=this._data[Ys+1],i.bg=this._data[Ys+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ue+0]=i.content,this._data[t*ue+1]=i.fg,this._data[t*ue+2]=i.bg}setCellFromCodepoint(t,i,s,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*ue+0]=i|s<<22,this._data[t*ue+1]=r.fg,this._data[t*ue+2]=r.bg}addCodepointToCell(t,i,s){let r=this._data[t*ue+0];r&2097152?this._combined[t]+=ti(i):r&2097151?(this._combined[t]=ti(r&2097151)+ti(i),r&=-2097152,r|=2097152):r=i|1<<22,s&&(r&=-12582913,r|=s<<22),this._data[t*ue+0]=r}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length-t){let r=new Rt;for(let n=this.length-t-i-1;n>=0;--n)this.setCell(t+i+n,this.loadCell(t+n,r));for(let n=0;n<i;++n)this.setCell(t+n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,i,s){if(t%=this.length,i<this.length-t){let r=new Rt;for(let n=0;n<this.length-t-i;++n)this.setCell(t+n,this.loadCell(t+i+n,r));for(let n=this.length-i;n<this.length;++n)this.setCell(n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,s)}replaceCells(t,i,s,r=!1){if(r){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.isProtected(t)||this.setCell(t,s),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.setCell(t++,s)}resize(t,i){if(t===this.length)return this._data.length*4*dn<this._data.buffer.byteLength;let s=t*ue;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let r=new Uint32Array(s);r.set(this._data),this._data=r}for(let r=this.length;r<t;++r)this.setCell(r,i)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let o=0;o<r.length;o++){let l=parseInt(r[o],10);l>=t&&delete this._combined[l]}let n=Object.keys(this._extendedAttrs);for(let o=0;o<n.length;o++){let l=parseInt(n[o],10);l>=t&&delete this._extendedAttrs[l]}}return this.length=t,s*4*dn<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*dn<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,t);return}this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new bh(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ue+0]&4194303)return t+(this._data[t*ue+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ue+0]&4194303||this._data[t*ue+2]&50331648)return t+(this._data[t*ue+0]>>22);return 0}copyCellsFrom(t,i,s,r,n){let o=t._data;if(n)for(let h=r-1;h>=0;h--){for(let a=0;a<ue;a++)this._data[(s+h)*ue+a]=o[(i+h)*ue+a];o[(i+h)*ue+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[i+h])}else for(let h=0;h<r;h++){for(let a=0;a<ue;a++)this._data[(s+h)*ue+a]=o[(i+h)*ue+a];o[(i+h)*ue+2]&268435456&&(this._extendedAttrs[s+h]=t._extendedAttrs[i+h])}let l=Object.keys(t._combined);for(let h=0;h<l.length;h++){let a=parseInt(l[h],10);a>=i&&(this._combined[a-i+s]=t._combined[a])}}translateToString(t,i,s,r){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;i<s;){let o=this._data[i*ue+0],l=o&2097151,h=o&2097152?this._combined[i]:l?ti(l):ii;if(n+=h,r)for(let a=0;a<h.length;++a)r.push(i);i+=o>>22||1}return r&&r.push(i),n}};function Kf(e,t,i,s,r,n){let o=[];for(let l=0;l<e.length-1;l++){let h=l,a=e.get(++h);if(!a.isWrapped)continue;let u=[e.get(l)];for(;h<e.length&&a.isWrapped;)u.push(a),a=e.get(++h);if(!n&&s>=l&&s<h){l+=u.length-1;continue}let d=0,m=fs(u,d,t),p=1,_=0;for(;p<u.length;){let y=fs(u,p,t),x=y-_,j=i-m,z=Math.min(x,j);u[d].copyCellsFrom(u[p],_,m,z,!1),m+=z,m===i&&(d++,m=0),_+=z,_===y&&(p++,_=0),m===0&&d!==0&&u[d-1].getWidth(i-1)===2&&(u[d].copyCellsFrom(u[d-1],i-1,m++,1,!1),u[d-1].setCell(i-1,r))}u[d].replaceCells(m,i,r);let g=0;for(let y=u.length-1;y>0&&(y>d||u[y].getTrimmedLength()===0);y--)g++;g>0&&(o.push(l+u.length-g),o.push(g)),l+=u.length-1}return o}function Uf(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let l=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:l}),o+=l-1,n+=l,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}function qf(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length}function Vf(e,t,i){let s=[],r=e.map((h,a)=>fs(e,a,t)).reduce((h,a)=>h+a),n=0,o=0,l=0;for(;l<r;){if(r-l<i){s.push(r-l);break}n+=i;let h=fs(e,o,t);n>h&&(n-=h,o++);let a=e[o].getWidth(n-1)===2;a&&n--;let u=a?i-1:i;s.push(u),l+=u}return s}function fs(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,r=e[t+1].getWidth(0)===2;return s&&r?i-1:i}var wh=class Ch{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Ch._nextId++,this._onDispose=this.register(new N),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),mi(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};wh._nextId=1;var jf=wh,Je={},fi=Je.B;Je[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Je.A={"#":"£"};Je.B=void 0;Je[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Je.C=Je[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Je.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Je.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Je.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Je.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Je.E=Je[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Je.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Je.H=Je[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Je["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var ul=4294967295,fl=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=je.clone(),this.savedCharset=fi,this.markers=[],this._nullCell=Rt.fromCharData([0,Il,1,0]),this._whitespaceCell=Rt.fromCharData([0,ii,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new cr,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new dl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new sr),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new sr),this._whitespaceCell}getBlankLine(e,t){return new ss(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>ul?ul:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=je);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new dl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(je),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let o=0;o<this.lines.length;o++)s+=+this.lines.get(o).resize(e,i);let n=0;if(this._rows<t)for(let o=this._rows;o<t;o++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new ss(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new ss(e,i)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let o=this.lines.length-r;o>0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=Kf(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(je),i);if(s.length>0){let r=Uf(this.lines,s);qf(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(je),r=i;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new ss(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(je),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let l=this.lines.get(o);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let h=[l];for(;l.isWrapped&&o>0;)l=this.lines.get(--o),h.unshift(l);if(!i){let z=this.ybase+this.y;if(z>=o&&z<o+h.length)continue}let a=h[h.length-1].getTrimmedLength(),u=Vf(h,this._cols,e),d=u.length-h.length,m;this.ybase===0&&this.y!==this.lines.length-1?m=Math.max(0,this.y-this.lines.maxLength+d):m=Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let z=0;z<d;z++){let C=this.getBlankLine(je,!0);p.push(C)}p.length>0&&(r.push({start:o+h.length+n,newLines:p}),n+=p.length),h.push(...p);let _=u.length-1,g=u[_];g===0&&(_--,g=u[_]);let y=h.length-d-1,x=a;for(;y>=0;){let z=Math.min(x,g);if(h[_]===void 0)break;if(h[_].copyCellsFrom(h[y],x-z,g-z,z,!0),g-=z,g===0&&(_--,g=u[_]),x-=z,x===0){y--;let C=Math.max(y,0);x=fs(h,C,this._cols)}}for(let z=0;z<h.length;z++)u[z]<e&&h[z].setCell(u[z],s);let j=d-m;for(;j-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(r.length>0){let o=[],l=[];for(let g=0;g<this.lines.length;g++)l.push(this.lines.get(g));let h=this.lines.length,a=h-1,u=0,d=r[u];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let m=0;for(let g=Math.min(this.lines.maxLength-1,h+n-1);g>=0;g--)if(d&&d.start>a+m){for(let y=d.newLines.length-1;y>=0;y--)this.lines.set(g--,d.newLines[y]);g++,o.push({index:a+1,amount:d.newLines.length}),m+=d.newLines.length,d=r[++u]}else this.lines.set(g,l[a--]);let p=0;for(let g=o.length-1;g>=0;g--)o[g].index+=p,this.lines.onInsertEmitter.fire(o[g]),p+=o[g].amount;let _=Math.max(0,h+n-this.lines.maxLength);_>0&&this.lines.onTrimEmitter.fire(_)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new jf(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Yf=class extends he{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new N),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new fl(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new fl(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},xh=2,kh=1,Zn=class extends he{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new N),this.onResize=this._onResize.event,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,xh),this.rows=Math.max(e.rawOptions.rows||0,kh),this.buffers=this._register(new Yf(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(i.scrollTop===0){let o=i.lines.isFull;n===i.lines.length-1?o?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),o?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let o=n-r+1;i.lines.shiftElements(r+1,o-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};Zn=He([K(0,ut)],Zn);var Di={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:hr,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},Gf=["normal","bold","100","200","300","400","500","600","700","800","900"],Xf=class extends he{constructor(e){super(),this._onOptionChange=this._register(new N),this.onOptionChange=this._onOptionChange.event;let t={...Di};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Te(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Di))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in Di))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Di[e]),!Jf(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Di[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=Gf.includes(t)?t:Di[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function Jf(e){return e==="block"||e==="underline"||e==="bar"}function rs(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&rs(e[s],t-1);return i}var pl=Object.freeze({insertMode:!1}),_l=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Qn=class extends he{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new N),this.onData=this._onData.event,this._onUserInput=this._register(new N),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new N),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new N),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=rs(pl),this.decPrivateModes=rs(_l)}reset(){this.modes=rs(pl),this.decPrivateModes=rs(_l)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};Qn=He([K(0,dt),K(1,Wl),K(2,ut)],Qn);var ml={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function un(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var fn=String.fromCharCode,gl={DEFAULT:e=>{let t=[un(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${fn(t[0])}${fn(t[1])}${fn(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${un(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${un(e,!0)};${e.x};${e.y}${t}`}},eo=class extends he{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new N),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(ml))this.addProtocol(s,ml[s]);for(let s of Object.keys(gl))this.addEncoding(s,gl[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};eo=He([K(0,dt),K(1,vi),K(2,ut)],eo);var pn=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Zf=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Xe;function Qf(e,t){let i=0,s=t.length-1,r;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=i;)if(r=i+s>>1,e>t[r][1])i=r+1;else if(e<t[r][0])s=r-1;else return!0;return!1}var ep=class{constructor(){if(this.version="6",!Xe){Xe=new Uint8Array(65536),Xe.fill(1),Xe[0]=0,Xe.fill(0,1,32),Xe.fill(0,127,160),Xe.fill(2,4352,4448),Xe[9001]=2,Xe[9002]=2,Xe.fill(2,11904,42192),Xe[12351]=1,Xe.fill(2,44032,55204),Xe.fill(2,63744,64256),Xe.fill(2,65040,65050),Xe.fill(2,65072,65136),Xe.fill(2,65280,65377),Xe.fill(2,65504,65511);for(let e=0;e<pn.length;++e)Xe.fill(0,pn[e][0],pn[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Xe[e]:Qf(e,Zf)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let r=pi.extractWidth(t);r===0?s=!1:r>i&&(i=r)}return pi.createPropertyValue(0,i,s)}},pi=class ir{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new N,this.onChange=this._onChange.event;let t=new ep;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let a=t.charCodeAt(n);56320<=a&&a<=57343?o=(o-55296)*1024+a-56320+65536:i+=this.wcwidth(a)}let l=this.charProperties(o,s),h=ir.extractWidth(l);ir.extractShouldJoin(l)&&(h-=ir.extractWidth(s)),i+=h,s=l}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},tp=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function vl(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var Ji=2147483647,ip=256,Eh=class to{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>ip)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new to;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let r=t[s];if(Array.isArray(r))for(let n=0;n<r.length;++n)i.addSubParam(r[n]);else i.addParam(r)}return i}clone(){let t=new to(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let i=0;i<this.length;++i){t.push(this.params[i]);let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Ji?Ji:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Ji?Ji:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&(t[i]=this._subParams.slice(s,r))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,r=s[i-1];s[i-1]=~r?Math.min(r*10+t,Ji):t}},Zi=[],sp=class{constructor(){this._state=0,this._active=Zi,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Zi}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Zi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Zi,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",ur(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let s=e[t++];if(s===59){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+s-48}this._state===2&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=Zi,this._id=-1,this._state=0}}},St=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=ur(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},Qi=[],rp=class{constructor(){this._handlers=Object.create(null),this._active=Qi,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Qi}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Qi,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Qi,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",ur(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=Qi,this._ident=0}},ns=new Eh;ns.addParam(0);var yl=class{constructor(e){this._handler=e,this._data="",this._params=ns,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ns,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=ur(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=ns,this._data="",this._hitLimit=!1,i));return this._params=ns,this._data="",this._hitLimit=!1,t}},np=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Et=160,op=(function(){let e=new np(4095),t=Array.apply(null,Array(256)).map((l,h)=>h),i=(l,h)=>t.slice(l,h),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n=i(0,14),o;e.setDefault(1,0),e.addMany(s,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Et,0,2,0),e.add(Et,8,5,8),e.add(Et,6,0,6),e.add(Et,11,0,11),e.add(Et,13,13,13),e})(),ap=class extends he{constructor(e=op){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Eh,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Te(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new sp),this._dcsParser=this._register(new rp),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s=0,r=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let l=this._parseStack.handlers,h=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&h>-1){for(;h>=0&&(o=l[h](this._params),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 4:if(i===!1&&h>-1){for(;h>=0&&(o=l[h](),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],o=this._oscParser.end(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let l=n;l<t;++l){switch(s=e[l],r=this._transitions.table[this.currentState<<8|(s<160?s:Et)],r>>4){case 2:for(let m=l+1;;++m){if(m>=t||(s=e[m])<32||s>126&&s<Et){this._printHandler(e,l,m),l=m-1;break}if(++m>=t||(s=e[m])<32||s>126&&s<Et){this._printHandler(e,l,m),l=m-1;break}if(++m>=t||(s=e[m])<32||s>126&&s<Et){this._printHandler(e,l,m),l=m-1;break}if(++m>=t||(s=e[m])<32||s>126&&s<Et){this._printHandler(e,l,m),l=m-1;break}}break;case 3:this._executeHandlers[s]?this._executeHandlers[s]():this._executeHandlerFb(s),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:l,code:s,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let h=this._csiHandlers[this._collect<<8|s],a=h?h.length-1:-1;for(;a>=0&&(o=h[a](this._params),o!==!0);a--)if(o instanceof Promise)return this._preserveStack(3,h,a,r,l),o;a<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++l<t&&(s=e[l])>47&&s<60);l--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let u=this._escHandlers[this._collect<<8|s],d=u?u.length-1:-1;for(;d>=0&&(o=u[d](),o!==!0);d--)if(o instanceof Promise)return this._preserveStack(4,u,d,r,l),o;d<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let m=l+1;;++m)if(m>=t||(s=e[m])===24||s===26||s===27||s>127&&s<Et){this._dcsParser.put(e,l,m),l=m-1;break}break;case 14:if(o=this._dcsParser.unhook(s!==24&&s!==26),o)return this._preserveStack(6,[],0,r,l),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let m=l+1;;m++)if(m>=t||(s=e[m])<32||s>127&&s<Et){this._oscParser.put(e,l,m),l=m-1;break}break;case 6:if(o=this._oscParser.end(s!==24&&s!==26),o)return this._preserveStack(5,[],0,r,l),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=r&15}}},lp=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,hp=/^[\da-f]+$/;function Sl(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let i=lp.exec(t);if(i){let s=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/s*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/s*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/s*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),hp.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,s=[0,0,0];for(let r=0;r<3;++r){let n=parseInt(t.slice(i*r,i*r+i),16);s[r]=i===1?n<<4:i===2?n:i===3?n>>4:n>>8}return s}}function _n(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function cp(e,t=16){let[i,s,r]=e;return`rgb:${_n(i,t)}/${_n(s,t)}/${_n(r,t)}`}var dp={"(":0,")":1,"*":2,"+":3,"-":1,".":2},ei=131072,bl=10;function wl(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Cl=5e3,xl=0,up=class extends he{constructor(e,t,i,s,r,n,o,l,h=new ap){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=l,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new nd,this._utf8Decoder=new od,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=je.clone(),this._eraseAttrDataInternal=je.clone(),this._onRequestBell=this._register(new N),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new N),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new N),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new N),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new N),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new N),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new N),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new N),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new N),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new N),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new N),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new N),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new io(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(a=>this._activeBuffer=a.activeBuffer)),this._parser.setCsiHandlerFallback((a,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(a),params:u.toArray()})}),this._parser.setEscHandlerFallback(a=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(a)})}),this._parser.setExecuteHandlerFallback(a=>{this._logService.debug("Unknown EXECUTE code: ",{code:a})}),this._parser.setOscHandlerFallback((a,u,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:a,action:u,data:d})}),this._parser.setDcsHandlerFallback((a,u,d)=>{u==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(a),action:u,payload:d})}),this._parser.setPrintHandler((a,u,d)=>this.print(a,u,d)),this._parser.registerCsiHandler({final:"@"},a=>this.insertChars(a)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},a=>this.scrollLeft(a)),this._parser.registerCsiHandler({final:"A"},a=>this.cursorUp(a)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},a=>this.scrollRight(a)),this._parser.registerCsiHandler({final:"B"},a=>this.cursorDown(a)),this._parser.registerCsiHandler({final:"C"},a=>this.cursorForward(a)),this._parser.registerCsiHandler({final:"D"},a=>this.cursorBackward(a)),this._parser.registerCsiHandler({final:"E"},a=>this.cursorNextLine(a)),this._parser.registerCsiHandler({final:"F"},a=>this.cursorPrecedingLine(a)),this._parser.registerCsiHandler({final:"G"},a=>this.cursorCharAbsolute(a)),this._parser.registerCsiHandler({final:"H"},a=>this.cursorPosition(a)),this._parser.registerCsiHandler({final:"I"},a=>this.cursorForwardTab(a)),this._parser.registerCsiHandler({final:"J"},a=>this.eraseInDisplay(a,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},a=>this.eraseInDisplay(a,!0)),this._parser.registerCsiHandler({final:"K"},a=>this.eraseInLine(a,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},a=>this.eraseInLine(a,!0)),this._parser.registerCsiHandler({final:"L"},a=>this.insertLines(a)),this._parser.registerCsiHandler({final:"M"},a=>this.deleteLines(a)),this._parser.registerCsiHandler({final:"P"},a=>this.deleteChars(a)),this._parser.registerCsiHandler({final:"S"},a=>this.scrollUp(a)),this._parser.registerCsiHandler({final:"T"},a=>this.scrollDown(a)),this._parser.registerCsiHandler({final:"X"},a=>this.eraseChars(a)),this._parser.registerCsiHandler({final:"Z"},a=>this.cursorBackwardTab(a)),this._parser.registerCsiHandler({final:"`"},a=>this.charPosAbsolute(a)),this._parser.registerCsiHandler({final:"a"},a=>this.hPositionRelative(a)),this._parser.registerCsiHandler({final:"b"},a=>this.repeatPrecedingCharacter(a)),this._parser.registerCsiHandler({final:"c"},a=>this.sendDeviceAttributesPrimary(a)),this._parser.registerCsiHandler({prefix:">",final:"c"},a=>this.sendDeviceAttributesSecondary(a)),this._parser.registerCsiHandler({final:"d"},a=>this.linePosAbsolute(a)),this._parser.registerCsiHandler({final:"e"},a=>this.vPositionRelative(a)),this._parser.registerCsiHandler({final:"f"},a=>this.hVPosition(a)),this._parser.registerCsiHandler({final:"g"},a=>this.tabClear(a)),this._parser.registerCsiHandler({final:"h"},a=>this.setMode(a)),this._parser.registerCsiHandler({prefix:"?",final:"h"},a=>this.setModePrivate(a)),this._parser.registerCsiHandler({final:"l"},a=>this.resetMode(a)),this._parser.registerCsiHandler({prefix:"?",final:"l"},a=>this.resetModePrivate(a)),this._parser.registerCsiHandler({final:"m"},a=>this.charAttributes(a)),this._parser.registerCsiHandler({final:"n"},a=>this.deviceStatus(a)),this._parser.registerCsiHandler({prefix:"?",final:"n"},a=>this.deviceStatusPrivate(a)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},a=>this.softReset(a)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},a=>this.setCursorStyle(a)),this._parser.registerCsiHandler({final:"r"},a=>this.setScrollRegion(a)),this._parser.registerCsiHandler({final:"s"},a=>this.saveCursor(a)),this._parser.registerCsiHandler({final:"t"},a=>this.windowOptions(a)),this._parser.registerCsiHandler({final:"u"},a=>this.restoreCursor(a)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},a=>this.insertColumns(a)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},a=>this.deleteColumns(a)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},a=>this.selectProtected(a)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},a=>this.requestMode(a,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},a=>this.requestMode(a,!1)),this._parser.setExecuteHandler(S.BEL,()=>this.bell()),this._parser.setExecuteHandler(S.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(S.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(S.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(S.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(S.BS,()=>this.backspace()),this._parser.setExecuteHandler(S.HT,()=>this.tab()),this._parser.setExecuteHandler(S.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(S.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(ls.IND,()=>this.index()),this._parser.setExecuteHandler(ls.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(ls.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new St(a=>(this.setTitle(a),this.setIconName(a),!0))),this._parser.registerOscHandler(1,new St(a=>this.setIconName(a))),this._parser.registerOscHandler(2,new St(a=>this.setTitle(a))),this._parser.registerOscHandler(4,new St(a=>this.setOrReportIndexedColor(a))),this._parser.registerOscHandler(8,new St(a=>this.setHyperlink(a))),this._parser.registerOscHandler(10,new St(a=>this.setOrReportFgColor(a))),this._parser.registerOscHandler(11,new St(a=>this.setOrReportBgColor(a))),this._parser.registerOscHandler(12,new St(a=>this.setOrReportCursorColor(a))),this._parser.registerOscHandler(104,new St(a=>this.restoreIndexedColor(a))),this._parser.registerOscHandler(110,new St(a=>this.restoreFgColor(a))),this._parser.registerOscHandler(111,new St(a=>this.restoreBgColor(a))),this._parser.registerOscHandler(112,new St(a=>this.restoreCursorColor(a))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let a in Je)this._parser.registerEscHandler({intermediates:"(",final:a},()=>this.selectCharset("("+a)),this._parser.registerEscHandler({intermediates:")",final:a},()=>this.selectCharset(")"+a)),this._parser.registerEscHandler({intermediates:"*",final:a},()=>this.selectCharset("*"+a)),this._parser.registerEscHandler({intermediates:"+",final:a},()=>this.selectCharset("+"+a)),this._parser.registerEscHandler({intermediates:"-",final:a},()=>this.selectCharset("-"+a)),this._parser.registerEscHandler({intermediates:".",final:a},()=>this.selectCharset("."+a)),this._parser.registerEscHandler({intermediates:"/",final:a},()=>this.selectCharset("/"+a));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(a=>(this._logService.error("Parsing error: ",a),a)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new yl((a,u)=>this.requestStatusString(a,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Cl))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Cl} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>ei&&(n=this._parseStack.position+ei)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,a=>String.fromCharCode(a)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(a=>a.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<ei&&(this._parseBuffer=new Uint32Array(Math.min(e.length,ei))),o||this._dirtyRowTracker.clearRange(),e.length>ei)for(let a=n;a<e.length;a+=ei){let u=a+ei<e.length?a+ei:e.length,d=typeof e=="string"?this._stringDecoder.decode(e.substring(a,u),this._parseBuffer):this._utf8Decoder.decode(e.subarray(a,u),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,d))return this._preserveStack(s,r,d,a),this._logSlowResolvingAsync(i),i}else if(!o){let a=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,a))return this._preserveStack(s,r,a,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let l=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(h,this._bufferService.rows-1),end:Math.min(l,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,l=this._bufferService.cols,h=this._coreService.decPrivateModes.wraparound,a=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let m=this._parser.precedingJoinState;for(let p=t;p<i;++p){if(s=e[p],s<127&&n){let x=n[String.fromCharCode(s)];x&&(s=x.charCodeAt(0))}let _=this._unicodeService.charProperties(s,m);r=pi.extractWidth(_);let g=pi.extractShouldJoin(_),y=g?pi.extractWidth(m):0;if(m=_,o&&this._onA11yChar.fire(ti(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-y>l){if(h){let x=d,j=this._activeBuffer.x-y;for(this._activeBuffer.x=y,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),y>0&&d instanceof ss&&d.copyCellsFrom(x,j,0,y,!1);j<l;)x.setCellFromCodepoint(j++,0,1,u)}else if(this._activeBuffer.x=l-1,r===2)continue}if(g&&this._activeBuffer.x){let x=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-x,s,r);for(let j=r-y;--j>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(a&&(d.insertCells(this._activeBuffer.x,r-y,this._activeBuffer.getNullCell(u)),d.getWidth(l-1)===2&&d.setCellFromCodepoint(l-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,s,r,u),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=m,this._activeBuffer.x<l&&i-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>wl(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new yl(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new St(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+i)?.getTrimmedLength(););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(je));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let i=e.params[0]||1,s=pi.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),l=0;for(let a=0;a<n.length;){let u=n.codePointAt(a)||0;o[l++]=u,a+=u>65535?2:1}let h=l;for(let a=1;a<i;++a)o.copyWithin(h,0,l),h+=l;return this.print(o,0,h),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(S.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(S.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(S.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(S.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(S.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,fi),this._charsetService.setgCharset(1,fi),this._charsetService.setgCharset(2,fi),this._charsetService.setgCharset(3,fi);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let i;(g=>(g[g.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",g[g.SET=1]="SET",g[g.RESET=2]="RESET",g[g.PERMANENTLY_SET=3]="PERMANENTLY_SET",g[g.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(i||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:l,cols:h}=this._bufferService,{active:a,alt:u}=l,d=this._optionsService.rawOptions,m=(g,y)=>(o.triggerDataEvent(`${S.ESC}[${t?"":"?"}${g};${y}$y`),!0),p=g=>g?1:2,_=e.params[0];return t?_===2?m(_,4):_===4?m(_,p(o.modes.insertMode)):_===12?m(_,3):_===20?m(_,p(d.convertEol)):m(_,0):_===1?m(_,p(s.applicationCursorKeys)):_===3?m(_,d.windowOptions.setWinLines?h===80?2:h===132?1:0:0):_===6?m(_,p(s.origin)):_===7?m(_,p(s.wraparound)):_===8?m(_,3):_===9?m(_,p(r==="X10")):_===12?m(_,p(d.cursorBlink)):_===25?m(_,p(!o.isCursorHidden)):_===45?m(_,p(s.reverseWraparound)):_===66?m(_,p(s.applicationKeypad)):_===67?m(_,4):_===1e3?m(_,p(r==="VT200")):_===1002?m(_,p(r==="DRAG")):_===1003?m(_,p(r==="ANY")):_===1004?m(_,p(s.sendFocus)):_===1005?m(_,4):_===1006?m(_,p(n==="SGR")):_===1015?m(_,4):_===1016?m(_,p(n==="SGR_PIXELS")):_===1048?m(_,1):_===47||_===1047||_===1049?m(_,p(a===u)):_===2004?m(_,p(s.bracketedPasteMode)):_===2026?m(_,p(s.synchronizedOutput)):m(_,0)}_updateAttrColor(e,t,i,s,r){return t===2?(e|=50331648,e&=-16777216,e|=ps.fromColorRGB([i,s,r])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),l=0;do s[1]===5&&(r=1),s[n+l+1+r]=o[l];while(++l<o.length&&l+n+1+r<s.length);break}if(s[1]===5&&n+r>=2||s[1]===2&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)s[o]===-1&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=je.fg,e.bg=je.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let r=0;r<t;r++)i=e.params[r],i>=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=je.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=je.bg&16777215):i===38||i===48||i===58?r+=this._extractColor(e,r,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=je.fg&16777215,s.bg&=-67108864,s.bg|=je.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${S.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${S.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${S.ESC}[?${t};${i}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=je.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!wl(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${S.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>bl&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>bl&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),r=i.shift();if(/^\d+$/.exec(s)){let n=parseInt(s);if(kl(n))if(r==="?")t.push({type:0,index:n});else{let o=Sl(r);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,r=i.findIndex(n=>n.startsWith("id="));return r!==-1&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Sl(i[s]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s<i.length;++s)if(/^\d+$/.exec(i[s])){let r=parseInt(i[s]);kl(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,fi),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(dp[e[0]],Je[e[1]]||fi),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=je.clone(),this._eraseAttrDataInternal=je.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Rt;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=o=>(this._coreService.triggerDataEvent(`${S.ESC}${o}${S.ESC}\\`),!0),s=this._bufferService.buffer,r=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},io=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(xl=e,e=t,t=xl),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};io=He([K(0,dt)],io);function kl(e){return 0<=e&&e<256}var fp=5e7,El=12,pp=50,_p=class extends he{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new N),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>fp)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],r=this._action(s,t);if(r){let o=l=>performance.now()-i>=El?setTimeout(()=>this._innerWrite(0,l)):this._innerWrite(i,l);r.catch(l=>(queueMicrotask(()=>{throw l}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=El)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>pp&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},so=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let l=t.addMarker(t.ybase+t.y),h={data:e,id:this._nextId++,lines:[l]};return l.onDispose(()=>this._removeMarkerFromLink(h,l)),this._dataByLinkId.set(h.id,h),h.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};so=He([K(0,dt)],so);var Rl=!1,mp=class extends he{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Li),this._onBinary=this._register(new N),this.onBinary=this._onBinary.event,this._onData=this._register(new N),this.onData=this._onData.event,this._onLineFeed=this._register(new N),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new N),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new N),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new N),this._instantiationService=new Hf,this.optionsService=this._register(new Xf(e)),this._instantiationService.setService(ut,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Zn)),this._instantiationService.setService(dt,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Jn)),this._instantiationService.setService(Wl,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Qn)),this._instantiationService.setService(vi,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(eo)),this._instantiationService.setService(Hl,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pi)),this._instantiationService.setService(cd,this.unicodeService),this._charsetService=this._instantiationService.createInstance(tp),this._instantiationService.setService(hd,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(so),this._instantiationService.setService(zl,this._oscLinkService),this._inputHandler=this._register(new up(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(rt.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(rt.forward(this._bufferService.onResize,this._onResize)),this._register(rt.forward(this.coreService.onData,this._onData)),this._register(rt.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new _p((t,i)=>this._inputHandler.parse(t,i))),this._register(rt.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new N),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Rl&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Rl=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,xh),t=Math.max(t,kh),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(vl.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(vl(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Te(()=>{for(let t of e)t.dispose()})}}},gp={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function vp(e,t,i,s){let r={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?r.key=S.ESC+"OA":r.key=S.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?r.key=S.ESC+"OD":r.key=S.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?r.key=S.ESC+"OC":r.key=S.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?r.key=S.ESC+"OB":r.key=S.ESC+"[B");break;case 8:r.key=e.ctrlKey?"\b":S.DEL,e.altKey&&(r.key=S.ESC+r.key);break;case 9:if(e.shiftKey){r.key=S.ESC+"[Z";break}r.key=S.HT,r.cancel=!0;break;case 13:r.key=e.altKey?S.ESC+S.CR:S.CR,r.cancel=!0;break;case 27:r.key=S.ESC,e.altKey&&(r.key=S.ESC+S.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;n?r.key=S.ESC+"[1;"+(n+1)+"D":t?r.key=S.ESC+"OD":r.key=S.ESC+"[D";break;case 39:if(e.metaKey)break;n?r.key=S.ESC+"[1;"+(n+1)+"C":t?r.key=S.ESC+"OC":r.key=S.ESC+"[C";break;case 38:if(e.metaKey)break;n?r.key=S.ESC+"[1;"+(n+1)+"A":t?r.key=S.ESC+"OA":r.key=S.ESC+"[A";break;case 40:if(e.metaKey)break;n?r.key=S.ESC+"[1;"+(n+1)+"B":t?r.key=S.ESC+"OB":r.key=S.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=S.ESC+"[2~");break;case 46:n?r.key=S.ESC+"[3;"+(n+1)+"~":r.key=S.ESC+"[3~";break;case 36:n?r.key=S.ESC+"[1;"+(n+1)+"H":t?r.key=S.ESC+"OH":r.key=S.ESC+"[H";break;case 35:n?r.key=S.ESC+"[1;"+(n+1)+"F":t?r.key=S.ESC+"OF":r.key=S.ESC+"[F";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=S.ESC+"[5;"+(n+1)+"~":r.key=S.ESC+"[5~";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=S.ESC+"[6;"+(n+1)+"~":r.key=S.ESC+"[6~";break;case 112:n?r.key=S.ESC+"[1;"+(n+1)+"P":r.key=S.ESC+"OP";break;case 113:n?r.key=S.ESC+"[1;"+(n+1)+"Q":r.key=S.ESC+"OQ";break;case 114:n?r.key=S.ESC+"[1;"+(n+1)+"R":r.key=S.ESC+"OR";break;case 115:n?r.key=S.ESC+"[1;"+(n+1)+"S":r.key=S.ESC+"OS";break;case 116:n?r.key=S.ESC+"[15;"+(n+1)+"~":r.key=S.ESC+"[15~";break;case 117:n?r.key=S.ESC+"[17;"+(n+1)+"~":r.key=S.ESC+"[17~";break;case 118:n?r.key=S.ESC+"[18;"+(n+1)+"~":r.key=S.ESC+"[18~";break;case 119:n?r.key=S.ESC+"[19;"+(n+1)+"~":r.key=S.ESC+"[19~";break;case 120:n?r.key=S.ESC+"[20;"+(n+1)+"~":r.key=S.ESC+"[20~";break;case 121:n?r.key=S.ESC+"[21;"+(n+1)+"~":r.key=S.ESC+"[21~";break;case 122:n?r.key=S.ESC+"[23;"+(n+1)+"~":r.key=S.ESC+"[23~";break;case 123:n?r.key=S.ESC+"[24;"+(n+1)+"~":r.key=S.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=S.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=S.DEL:e.keyCode===219?r.key=S.ESC:e.keyCode===220?r.key=S.FS:e.keyCode===221&&(r.key=S.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let o=gp[e.keyCode]?.[e.shiftKey?1:0];if(o)r.key=S.ESC+o;else if(e.keyCode>=65&&e.keyCode<=90){let l=e.ctrlKey?e.keyCode-64:e.keyCode+32,h=String.fromCharCode(l);e.shiftKey&&(h=h.toUpperCase()),r.key=S.ESC+h}else if(e.keyCode===32)r.key=S.ESC+(e.ctrlKey?S.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let l=e.code.slice(3,4);e.shiftKey||(l=l.toLowerCase()),r.key=S.ESC+l,r.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(r.key=S.US),e.key==="@"&&(r.key=S.NUL));break}return r}var $e=0,yp=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new cr,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new cr,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,n)=>this._getKey(r)-this._getKey(n)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||($e=this._search(t),$e===-1)||this._getKey(this._array[$e])!==t)return!1;do if(this._array[$e]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push($e),!0;while(++$e<this._array.length&&this._getKey(this._array[$e])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((r,n)=>r-n),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&($e=this._search(e),!($e<0||$e>=this._array.length)&&this._getKey(this._array[$e])===e))do yield this._array[$e];while(++$e<this._array.length&&this._getKey(this._array[$e])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&($e=this._search(e),!($e<0||$e>=this._array.length)&&this._getKey(this._array[$e])===e))do t(this._array[$e]);while(++$e<this._array.length&&this._getKey(this._array[$e])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else if(r<e)t=s+1;else{for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},mn=0,Tl=0,Sp=class extends he{constructor(){super(),this._decorations=new yp(e=>e?.marker.line),this._onDecorationRegistered=this._register(new N),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new N),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Te(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new bp(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,r=>{mn=r.options.x??0,Tl=mn+(r.options.width??1),e>=mn&&e<Tl&&(!i||(r.options.layer??"bottom")===i)&&s(r)})}},bp=class extends si{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new N),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new N),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Be.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Be.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},wp=1e3,Cp=class{constructor(e,t=wp){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=s-this._lastRefreshMs,n=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Dl=20,Bl=!1,dr=class extends he{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Cp(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");Bl?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=r.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(r.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(r.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
55
|
-
`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(
|
|
56
|
-
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Dl+1&&(this._liveRegion.textContent+=vn.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let n=i.lines.get(i.ydisp+r),o=[],l=n?.translateToString(!0,void 0,void 0,o)||"",h=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(l.length===0?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=l,this._rowColumns.set(a,o)),a.setAttribute("aria-posinset",h),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],r=i.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(r===n||e.relatedTarget!==s)return;let o,l;if(t===0?(o=i,l=this._rowElements.pop(),this._rowContainer.removeChild(l)):(o=this._rowElements.shift(),l=i,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),l.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;let r=({node:l,offset:h})=>{let a=l instanceof Text?l.parentNode:l,u=parseInt(a?.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(a);if(!d)return console.warn("columns is null. Race condition?"),null;let m=h<d.length?d[h]:d.slice(-1)[0]+1;return m>=this._terminal.cols&&(++u,m=0),{row:u,column:m}},n=r(t),o=r(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform="";let t=e.getBoundingClientRect().width,i=this._rowColumns.get(e)?.slice(-1)?.[0];if(!i)return;let s=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};dr=He([K(1,no),K(2,Vt),K(3,jt)],dr);var ro=class extends he{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new N),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new N),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Te(()=>{mi(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(ie(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(ie(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(ie(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(ie(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s<i.length;s++){let r=i[s];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(s=>{s?.forEach(r=>{r.link.dispose&&r.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[s,r]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(s)&&(i=this._checkLinkProviderResult(s,e,i)):r.provideLinks(e.y,n=>{if(this._isMouseOut)return;let o=n?.map(l=>({link:l}));this._activeProviderReplies?.set(s,o),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let n=0;n<r.length;n++){let o=r[n],l=o.link.range.start.y<e?0:o.link.range.start.x,h=o.link.range.end.y>e?this._bufferService.cols:o.link.range.end.x;for(let a=l;a<=h;a++){if(i.has(a)){r.splice(n--,1);break}i.add(a)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),r=!1;for(let n=0;n<e;n++)(!this._activeProviderReplies.has(n)||this._activeProviderReplies.get(n))&&(r=!0);if(!r&&s){let n=s.find(o=>this._linkAtPosition(o.link,t));n&&(i=!0,this._handleNewLink(n))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let n=0;n<this._activeProviderReplies.size;n++){let o=this._activeProviderReplies.get(n)?.find(l=>this._linkAtPosition(l.link,t));if(o){i=!0,this._handleNewLink(o);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&xp(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,mi(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:i=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:i=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(s,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};ro=He([K(1,oo),K(2,jt),K(3,dt),K(4,Kl)],ro);function xp(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var kp=class extends mp{constructor(e={}){super(e),this._linkifier=this._register(new Li),this.browser=fh,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Li),this._onCursorMove=this._register(new N),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new N),this.onKey=this._onKey.event,this._onRender=this._register(new N),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new N),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new N),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new N),this.onBell=this._onBell.event,this._onFocus=this._register(new N),this._onBlur=this._register(new N),this._onA11yCharEmitter=this._register(new N),this._onA11yTabEmitter=this._register(new N),this._onWillOpen=this._register(new N),this._setup(),this._decorationService=this._instantiationService.createInstance(Sp),this._instantiationService.setService(_s,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(ff),this._instantiationService.setService(Kl,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Sn)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(rt.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(rt.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(rt.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(rt.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Te(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let r=Re.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${S.ESC}]${s};${cp(r)}${$n.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=Ke.toColor(...t.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=Ke.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(dr,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(S.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(S.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,l=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=l+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(ie(this.element,"copy",t=>{this.hasSelection()&&sd(t,this._selectionService)}));let e=t=>rd(t,this.textarea,this.coreService,this.optionsService);this._register(ie(this.textarea,"paste",e)),this._register(ie(this.element,"paste",e)),ph?this._register(ie(this.element,"mousedown",t=>{t.button===2&&Ta(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(ie(this.element,"contextmenu",t=>{Ta(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),_o&&this._register(ie(this.element,"auxclick",t=>{t.button===1&&Pl(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(ie(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(ie(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(ie(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(ie(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(ie(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(ie(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(ie(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(ie(this.screenElement,"mousemove",r=>this.updateCursorStyle(r))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",gn.get()),gh||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(df,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Vt,this._coreBrowserService),this._register(ie(this.textarea,"focus",r=>this._handleTextAreaFocus(r))),this._register(ie(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Vn,this._document,this._helperContainer),this._instantiationService.setService(fr,this._charSizeService),this._themeService=this._instantiationService.createInstance(Xn),this._instantiationService.setService(Ai,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(lr),this._instantiationService.setService($l,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Yn,this.rows,this.screenElement)),this._instantiationService.setService(jt,this._renderService),this._register(this._renderService.onRenderedViewportChange(r=>this._onRender.fire(r))),this.onResize(r=>this._renderService.resize(r.cols,r.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(Kn,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(jn),this._instantiationService.setService(oo,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(ro,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Wn,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(r=>{super.scrollLines(r,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Gn,this.element,this.screenElement,s)),this._instantiationService.setService(ud,this._selectionService),this._register(this._selectionService.onRequestScrollLines(r=>this.scrollLines(r.amount,r.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(r=>this._renderService.handleSelectionChanged(r.start,r.end,r.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(r=>{this.textarea.value=r,this.textarea.focus(),this.textarea.select()})),this._register(rt.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(zn,this.screenElement)),this._register(ie(this.element,"mousedown",r=>this._selectionService.handleMouseDown(r))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(dr,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",r=>this._handleScreenReaderModeOptionChange(r))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ar,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",r=>{!this._overviewRulerRenderer&&r&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ar,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(qn,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(n){let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let l,h;switch(n.overrideType||n.type){case"mousemove":h=32,n.buttons===void 0?(l=3,n.button!==void 0&&(l=n.button<3?n.button:3)):l=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":h=0,l=n.button<3?n.button:3;break;case"mousedown":h=1,l=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let a=n.deltaY;if(a===0||e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;h=a<0?0:1,l=4;break;default:return!1}return h===void 0||l===void 0||l>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:l,action:h,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),n&16?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),n&2?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),n&4?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(ie(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(n)})),this._register(ie(t,"wheel",n=>{if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(n,!0);let o=S.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(o,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Ml(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=vp(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===S.ETX||i.key===S.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Ep(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(je));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(S.ESC+"[I"):this.coreService.triggerDataEvent(S.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${S.ESC}[4;${i};${t}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${S.ESC}[6;${r};${s}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Ep(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Rp=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Tp=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Rt)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Ll=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Tp(t)}getNullCell(){return new Rt}},Dp=class extends he{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new N),this.onBufferChange=this._onBufferChange.event,this._normal=new Ll(this._core.buffers.normal,"normal"),this._alternate=new Ll(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Bp=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},Lp=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},Ap=["cols","rows"],Nt=0,Rh=class extends he{constructor(e){super(),this._core=this._register(new kp(e)),this._addonManager=this._register(new Rp),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,r)=>{this._checkReadonlyOptions(s),this._core.options[s]=r};for(let s in this._core.options){let r={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,r)}}_checkReadonlyOptions(e){if(Ap.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Bp(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Lp(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new Dp(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
57
|
-
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return
|
|
54
|
+
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Io&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=bl(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Po(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-Dn),Dn),t/=Dn,t/Math.abs(t)+Math.round(t*(If-1)))}shouldForceSelection(e){return Tr?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Of)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Tr&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let s=i.lines.get(this._model.selectionEnd[1]);s&&s.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Nf&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let s=Rf(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(s,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),l=this._convertViewportColToCharacterIndex(n,e[0]),c=l,a=e[0]-l,u=0,d=0,_=0,m=0;if(o.charAt(l)===" "){for(;l>0&&o.charAt(l-1)===" ";)l--;for(;c<o.length&&o.charAt(c+1)===" ";)c++}else{let y=e[0],x=e[0];n.getWidth(y)===0&&(u++,y--),n.getWidth(x)===2&&(d++,x++);let q=n.getString(x).length;for(q>1&&(m+=q-1,c+=q-1);y>0&&l>0&&!this._isCharWordSeparator(n.loadCell(y-1,this._workCell));){n.loadCell(y-1,this._workCell);let W=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,y--):W>1&&(_+=W-1,l-=W-1),l--,y--}for(;x<n.length&&c+1<o.length&&!this._isCharWordSeparator(n.loadCell(x+1,this._workCell));){n.loadCell(x+1,this._workCell);let W=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,x++):W>1&&(m+=W-1,c+=W-1),c++,x++}}c++;let p=l+a-u+_,g=Math.min(this._bufferService.cols,c-l+u+d-_-m);if(!(!t&&o.slice(l,c).trim()==="")){if(i&&p===0&&n.getCodePoint(0)!==32){let y=r.lines.get(e[1]-1);if(y&&n.isWrapped&&y.getCodePoint(this._bufferService.cols-1)!==32){let x=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(x){let q=this._bufferService.cols-x.start;p-=q,g+=q}}}if(s&&p+g===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let y=r.lines.get(e[1]+1);if(y?.isWrapped&&y.getCodePoint(0)!==32){let x=this._getWordAt([0,e[1]+1],!1,!1,!0);x&&(g+=x.length)}}return{start:p,length:g}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=bl(i,this._bufferService.cols)}};mo=ze([U(3,St),U(4,Oi),U(5,Ro),U(6,bt),U(7,ni),U(8,ri)],mo);var wl=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Cl=class{constructor(){this._color=new wl,this._css=new wl}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},tt=Object.freeze((()=>{let e=[Pe.toColor("#2e3436"),Pe.toColor("#cc0000"),Pe.toColor("#4e9a06"),Pe.toColor("#c4a000"),Pe.toColor("#3465a4"),Pe.toColor("#75507b"),Pe.toColor("#06989a"),Pe.toColor("#d3d7cf"),Pe.toColor("#555753"),Pe.toColor("#ef2929"),Pe.toColor("#8ae234"),Pe.toColor("#fce94f"),Pe.toColor("#729fcf"),Pe.toColor("#ad7fa8"),Pe.toColor("#34e2e2"),Pe.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:Ye.toCss(s,r,n),rgba:Ye.toRgba(s,r,n)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ye.toCss(s,s,s),rgba:Ye.toRgba(s,s,s)})}return e})()),Di=Pe.toColor("#ffffff"),bs=Pe.toColor("#000000"),xl=Pe.toColor("#ffffff"),kl=bs,_s={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Wf=Di,go=class extends ve{constructor(e){super(),this._optionsService=e,this._contrastCache=new Cl,this._halfContrastCache=new Cl,this._onChangeColors=this._register(new N),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Di,background:bs,cursor:xl,cursorAccent:kl,selectionForeground:void 0,selectionBackgroundTransparent:_s,selectionBackgroundOpaque:Ae.blend(bs,_s),selectionInactiveBackgroundTransparent:_s,selectionInactiveBackgroundOpaque:Ae.blend(bs,_s),scrollbarSliderBackground:Ae.opacity(Di,.2),scrollbarSliderHoverBackground:Ae.opacity(Di,.4),scrollbarSliderActiveBackground:Ae.opacity(Di,.5),overviewRulerBorder:Di,ansi:tt.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Te(e.foreground,Di),t.background=Te(e.background,bs),t.cursor=Ae.blend(t.background,Te(e.cursor,xl)),t.cursorAccent=Ae.blend(t.background,Te(e.cursorAccent,kl)),t.selectionBackgroundTransparent=Te(e.selectionBackground,_s),t.selectionBackgroundOpaque=Ae.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Te(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Ae.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Te(e.selectionForeground,vl):void 0,t.selectionForeground===vl&&(t.selectionForeground=void 0),Ae.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Ae.opacity(t.selectionBackgroundTransparent,.3)),Ae.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Ae.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Te(e.scrollbarSliderBackground,Ae.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Te(e.scrollbarSliderHoverBackground,Ae.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Te(e.scrollbarSliderActiveBackground,Ae.opacity(t.foreground,.5)),t.overviewRulerBorder=Te(e.overviewRulerBorder,Wf),t.ansi=tt.slice(),t.ansi[0]=Te(e.black,tt[0]),t.ansi[1]=Te(e.red,tt[1]),t.ansi[2]=Te(e.green,tt[2]),t.ansi[3]=Te(e.yellow,tt[3]),t.ansi[4]=Te(e.blue,tt[4]),t.ansi[5]=Te(e.magenta,tt[5]),t.ansi[6]=Te(e.cyan,tt[6]),t.ansi[7]=Te(e.white,tt[7]),t.ansi[8]=Te(e.brightBlack,tt[8]),t.ansi[9]=Te(e.brightRed,tt[9]),t.ansi[10]=Te(e.brightGreen,tt[10]),t.ansi[11]=Te(e.brightYellow,tt[11]),t.ansi[12]=Te(e.brightBlue,tt[12]),t.ansi[13]=Te(e.brightMagenta,tt[13]),t.ansi[14]=Te(e.brightCyan,tt[14]),t.ansi[15]=Te(e.brightWhite,tt[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=Te(e.extendedAnsi[s],tt[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};go=ze([U(0,bt)],go);function Te(e,t){if(e!==void 0)try{return Pe.toColor(e)}catch{}return t}var zf=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},$f=class{constructor(){this._services=new zf,this._services.set(Eo,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=hd(e).sort((n,o)=>n.index-o.index),s=[];for(let n of i){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);s.push(o)}let r=i.length>0?i[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},Kf={trace:0,debug:1,info:2,warn:3,error:4,off:5},Uf="xterm.js: ",vo=class extends ve{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),qf=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Kf[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":Uf)+t,...i)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};vo=ze([U(0,bt)],vo);var qf,El=class extends ve{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new N),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new N),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new N),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let s=e;s<this._length-t;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Se=3,Je=Object.freeze(new Ms),pr=0,An=2,ws=class Oc{constructor(t,i,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*Se);let r=i||Nt.fromCharData([0,Xl,1,0]);for(let n=0;n<t;++n)this.setCell(n,r);this.length=t}get(t){let i=this._data[t*Se+0],s=i&2097151;return[this._data[t*Se+1],i&2097152?this._combined[t]:s?_i(s):"",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*Se+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*Se+0]=t|2097152|i[2]<<22):this._data[t*Se+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*Se+0]>>22}hasWidth(t){return this._data[t*Se+0]&12582912}getFg(t){return this._data[t*Se+1]}getBg(t){return this._data[t*Se+2]}hasContent(t){return this._data[t*Se+0]&4194303}getCodePoint(t){let i=this._data[t*Se+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*Se+0]&2097152}getString(t){let i=this._data[t*Se+0];return i&2097152?this._combined[t]:i&2097151?_i(i&2097151):""}isProtected(t){return this._data[t*Se+2]&536870912}loadCell(t,i){return pr=t*Se,i.content=this._data[pr+0],i.fg=this._data[pr+1],i.bg=this._data[pr+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Se+0]=i.content,this._data[t*Se+1]=i.fg,this._data[t*Se+2]=i.bg}setCellFromCodepoint(t,i,s,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*Se+0]=i|s<<22,this._data[t*Se+1]=r.fg,this._data[t*Se+2]=r.bg}addCodepointToCell(t,i,s){let r=this._data[t*Se+0];r&2097152?this._combined[t]+=_i(i):r&2097151?(this._combined[t]=_i(r&2097151)+_i(i),r&=-2097152,r|=2097152):r=i|1<<22,s&&(r&=-12582913,r|=s<<22),this._data[t*Se+0]=r}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length-t){let r=new Nt;for(let n=this.length-t-i-1;n>=0;--n)this.setCell(t+i+n,this.loadCell(t+n,r));for(let n=0;n<i;++n)this.setCell(t+n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,i,s){if(t%=this.length,i<this.length-t){let r=new Nt;for(let n=0;n<this.length-t-i;++n)this.setCell(t+n,this.loadCell(t+i+n,r));for(let n=this.length-i;n<this.length;++n)this.setCell(n,s)}else for(let r=t;r<this.length;++r)this.setCell(r,s);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,s)}replaceCells(t,i,s,r=!1){if(r){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.isProtected(t)||this.setCell(t,s),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,s);t<i&&t<this.length;)this.setCell(t++,s)}resize(t,i){if(t===this.length)return this._data.length*4*An<this._data.buffer.byteLength;let s=t*Se;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let r=new Uint32Array(s);r.set(this._data),this._data=r}for(let r=this.length;r<t;++r)this.setCell(r,i)}else{this._data=this._data.subarray(0,s);let r=Object.keys(this._combined);for(let o=0;o<r.length;o++){let l=parseInt(r[o],10);l>=t&&delete this._combined[l]}let n=Object.keys(this._extendedAttrs);for(let o=0;o<n.length;o++){let l=parseInt(n[o],10);l>=t&&delete this._extendedAttrs[l]}}return this.length=t,s*4*An<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*An<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,t);return}this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new Oc(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Se+0]&4194303)return t+(this._data[t*Se+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Se+0]&4194303||this._data[t*Se+2]&50331648)return t+(this._data[t*Se+0]>>22);return 0}copyCellsFrom(t,i,s,r,n){let o=t._data;if(n)for(let c=r-1;c>=0;c--){for(let a=0;a<Se;a++)this._data[(s+c)*Se+a]=o[(i+c)*Se+a];o[(i+c)*Se+2]&268435456&&(this._extendedAttrs[s+c]=t._extendedAttrs[i+c])}else for(let c=0;c<r;c++){for(let a=0;a<Se;a++)this._data[(s+c)*Se+a]=o[(i+c)*Se+a];o[(i+c)*Se+2]&268435456&&(this._extendedAttrs[s+c]=t._extendedAttrs[i+c])}let l=Object.keys(t._combined);for(let c=0;c<l.length;c++){let a=parseInt(l[c],10);a>=i&&(this._combined[a-i+s]=t._combined[a])}}translateToString(t,i,s,r){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;i<s;){let o=this._data[i*Se+0],l=o&2097151,c=o&2097152?this._combined[i]:l?_i(l):mi;if(n+=c,r)for(let a=0;a<c.length;++a)r.push(i);i+=o>>22||1}return r&&r.push(i),n}};function Vf(e,t,i,s,r,n){let o=[];for(let l=0;l<e.length-1;l++){let c=l,a=e.get(++c);if(!a.isWrapped)continue;let u=[e.get(l)];for(;c<e.length&&a.isWrapped;)u.push(a),a=e.get(++c);if(!n&&s>=l&&s<c){l+=u.length-1;continue}let d=0,_=Bs(u,d,t),m=1,p=0;for(;m<u.length;){let y=Bs(u,m,t),x=y-p,q=i-_,W=Math.min(x,q);u[d].copyCellsFrom(u[m],p,_,W,!1),_+=W,_===i&&(d++,_=0),p+=W,p===y&&(m++,p=0),_===0&&d!==0&&u[d-1].getWidth(i-1)===2&&(u[d].copyCellsFrom(u[d-1],i-1,_++,1,!1),u[d-1].setCell(i-1,r))}u[d].replaceCells(_,i,r);let g=0;for(let y=u.length-1;y>0&&(y>d||u[y].getTrimmedLength()===0);y--)g++;g>0&&(o.push(l+u.length-g),o.push(g)),l+=u.length-1}return o}function jf(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let l=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:l}),o+=l-1,n+=l,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}function Yf(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length}function Gf(e,t,i){let s=[],r=e.map((c,a)=>Bs(e,a,t)).reduce((c,a)=>c+a),n=0,o=0,l=0;for(;l<r;){if(r-l<i){s.push(r-l);break}n+=i;let c=Bs(e,o,t);n>c&&(n-=c,o++);let a=e[o].getWidth(n-1)===2;a&&n--;let u=a?i-1:i;s.push(u),l+=u}return s}function Bs(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,r=e[t+1].getWidth(0)===2;return s&&r?i-1:i}var Nc=class Fc{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Fc._nextId++,this._onDispose=this.register(new N),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Pi(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Nc._nextId=1;var Xf=Nc,st={},Ai=st.B;st[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};st.A={"#":"£"};st.B=void 0;st[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};st.C=st[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};st.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};st.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};st.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};st.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};st.E=st[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};st.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};st.H=st[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};st["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Rl=4294967295,Ll=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Je.clone(),this.savedCharset=Ai,this.markers=[],this._nullCell=Nt.fromCharData([0,Xl,1,0]),this._whitespaceCell=Nt.fromCharData([0,mi,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Dr,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new El(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Cr),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Cr),this._whitespaceCell}getBlankLine(e,t){return new ws(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Rl?Rl:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Je);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new El(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Je),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let o=0;o<this.lines.length;o++)s+=+this.lines.get(o).resize(e,i);let n=0;if(this._rows<t)for(let o=this._rows;o<t;o++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new ws(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new ws(e,i)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let o=this.lines.length-r;o>0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=Vf(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Je),i);if(s.length>0){let r=jf(this.lines,s);Yf(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Je),r=i;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new ws(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(Je),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let l=this.lines.get(o);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let c=[l];for(;l.isWrapped&&o>0;)l=this.lines.get(--o),c.unshift(l);if(!i){let W=this.ybase+this.y;if(W>=o&&W<o+c.length)continue}let a=c[c.length-1].getTrimmedLength(),u=Gf(c,this._cols,e),d=u.length-c.length,_;this.ybase===0&&this.y!==this.lines.length-1?_=Math.max(0,this.y-this.lines.maxLength+d):_=Math.max(0,this.lines.length-this.lines.maxLength+d);let m=[];for(let W=0;W<d;W++){let k=this.getBlankLine(Je,!0);m.push(k)}m.length>0&&(r.push({start:o+c.length+n,newLines:m}),n+=m.length),c.push(...m);let p=u.length-1,g=u[p];g===0&&(p--,g=u[p]);let y=c.length-d-1,x=a;for(;y>=0;){let W=Math.min(x,g);if(c[p]===void 0)break;if(c[p].copyCellsFrom(c[y],x-W,g-W,W,!0),g-=W,g===0&&(p--,g=u[p]),x-=W,x===0){y--;let k=Math.max(y,0);x=Bs(c,k,this._cols)}}for(let W=0;W<c.length;W++)u[W]<e&&c[W].setCell(u[W],s);let q=d-_;for(;q-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(r.length>0){let o=[],l=[];for(let g=0;g<this.lines.length;g++)l.push(this.lines.get(g));let c=this.lines.length,a=c-1,u=0,d=r[u];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let _=0;for(let g=Math.min(this.lines.maxLength-1,c+n-1);g>=0;g--)if(d&&d.start>a+_){for(let y=d.newLines.length-1;y>=0;y--)this.lines.set(g--,d.newLines[y]);g++,o.push({index:a+1,amount:d.newLines.length}),_+=d.newLines.length,d=r[++u]}else this.lines.set(g,l[a--]);let m=0;for(let g=o.length-1;g>=0;g--)o[g].index+=m,this.lines.onInsertEmitter.fire(o[g]),m+=o[g].amount;let p=Math.max(0,c+n-this.lines.maxLength);p>0&&this.lines.onTrimEmitter.fire(p)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Xf(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Jf=class extends ve{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new N),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ll(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ll(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Hc=2,Wc=1,yo=class extends ve{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new N),this.onResize=this._onResize.event,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Hc),this.rows=Math.max(e.rawOptions.rows||0,Wc),this.buffers=this._register(new Jf(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(i.scrollTop===0){let o=i.lines.isFull;n===i.lines.length-1?o?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),o?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let o=n-r+1;i.lines.shiftElements(r+1,o-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};yo=ze([U(0,bt)],yo);var ji={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Tr,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},Zf=["normal","bold","100","200","300","400","500","600","700","800","900"],Qf=class extends ve{constructor(e){super(),this._onOptionChange=this._register(new N),this.onOptionChange=this._onOptionChange.event;let t={...ji};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Be(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in ji))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in ji))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=ji[e]),!ep(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=ji[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=Zf.includes(t)?t:ji[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function ep(e){return e==="block"||e==="underline"||e==="bar"}function Cs(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Cs(e[s],t-1);return i}var Tl=Object.freeze({insertMode:!1}),Dl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),So=class extends ve{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new N),this.onData=this._onData.event,this._onUserInput=this._register(new N),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new N),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new N),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Cs(Tl),this.decPrivateModes=Cs(Dl)}reset(){this.modes=Cs(Tl),this.decPrivateModes=Cs(Dl)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};So=ze([U(0,St),U(1,tc),U(2,bt)],So);var Al={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function Bn(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var Mn=String.fromCharCode,Bl={DEFAULT:e=>{let t=[Bn(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${Mn(t[0])}${Mn(t[1])}${Mn(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Bn(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Bn(e,!0)};${e.x};${e.y}${t}`}},bo=class extends ve{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new N),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Al))this.addProtocol(s,Al[s]);for(let s of Object.keys(Bl))this.addEncoding(s,Bl[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};bo=ze([U(0,St),U(1,Oi),U(2,bt)],bo);var Pn=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],tp=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],it;function ip(e,t){let i=0,s=t.length-1,r;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=i;)if(r=i+s>>1,e>t[r][1])i=r+1;else if(e<t[r][0])s=r-1;else return!0;return!1}var sp=class{constructor(){if(this.version="6",!it){it=new Uint8Array(65536),it.fill(1),it[0]=0,it.fill(0,1,32),it.fill(0,127,160),it.fill(2,4352,4448),it[9001]=2,it[9002]=2,it.fill(2,11904,42192),it[12351]=1,it.fill(2,44032,55204),it.fill(2,63744,64256),it.fill(2,65040,65050),it.fill(2,65072,65136),it.fill(2,65280,65377),it.fill(2,65504,65511);for(let e=0;e<Pn.length;++e)it.fill(0,Pn[e][0],Pn[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?it[e]:ip(e,tp)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let r=Bi.extractWidth(t);r===0?s=!1:r>i&&(i=r)}return Bi.createPropertyValue(0,i,s)}},Bi=class wr{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new N,this.onChange=this._onChange.event;let t=new sp;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let a=t.charCodeAt(n);56320<=a&&a<=57343?o=(o-55296)*1024+a-56320+65536:i+=this.wcwidth(a)}let l=this.charProperties(o,s),c=wr.extractWidth(l);wr.extractShouldJoin(l)&&(c-=wr.extractWidth(s)),i+=c,s=l}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},rp=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ml(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var ms=2147483647,np=256,zc=class wo{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>np)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new wo;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let r=t[s];if(Array.isArray(r))for(let n=0;n<r.length;++n)i.addSubParam(r[n]);else i.addParam(r)}return i}clone(){let t=new wo(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let i=0;i<this.length;++i){t.push(this.params[i]);let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>ms?ms:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>ms?ms:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let s=this._subParamsIdx[i]>>8,r=this._subParamsIdx[i]&255;r-s>0&&(t[i]=this._subParams.slice(s,r))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,r=s[i-1];s[i-1]=~r?Math.min(r*10+t,ms):t}},gs=[],op=class{constructor(){this._state=0,this._active=gs,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=gs}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=gs,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||gs,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Br(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let s=e[t++];if(s===59){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+s-48}this._state===2&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=gs,this._id=-1,this._state=0}}},Tt=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Br(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},vs=[],ap=class{constructor(){this._handlers=Object.create(null),this._active=vs,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vs}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=vs,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vs,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Br(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=vs,this._ident=0}},xs=new zc;xs.addParam(0);var Pl=class{constructor(e){this._handler=e,this._data="",this._params=xs,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():xs,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Br(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=xs,this._data="",this._hitLimit=!1,i));return this._params=xs,this._data="",this._hitLimit=!1,t}},lp=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Ot=160,cp=(function(){let e=new lp(4095),t=Array.apply(null,Array(256)).map((l,c)=>c),i=(l,c)=>t.slice(l,c),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n=i(0,14),o;e.setDefault(1,0),e.addMany(s,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Ot,0,2,0),e.add(Ot,8,5,8),e.add(Ot,6,0,6),e.add(Ot,11,0,11),e.add(Ot,13,13,13),e})(),hp=class extends ve{constructor(e=cp){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new zc,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Be(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new op),this._dcsParser=this._register(new ap),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s=0,r=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let l=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&c>-1){for(;c>=0&&(o=l[c](this._params),o!==!0);c--)if(o instanceof Promise)return this._parseStack.handlerPos=c,o}this._parseStack.handlers=[];break;case 4:if(i===!1&&c>-1){for(;c>=0&&(o=l[c](),o!==!0);c--)if(o instanceof Promise)return this._parseStack.handlerPos=c,o}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],o=this._oscParser.end(s!==24&&s!==26,i),o)return o;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let l=n;l<t;++l){switch(s=e[l],r=this._transitions.table[this.currentState<<8|(s<160?s:Ot)],r>>4){case 2:for(let _=l+1;;++_){if(_>=t||(s=e[_])<32||s>126&&s<Ot){this._printHandler(e,l,_),l=_-1;break}if(++_>=t||(s=e[_])<32||s>126&&s<Ot){this._printHandler(e,l,_),l=_-1;break}if(++_>=t||(s=e[_])<32||s>126&&s<Ot){this._printHandler(e,l,_),l=_-1;break}if(++_>=t||(s=e[_])<32||s>126&&s<Ot){this._printHandler(e,l,_),l=_-1;break}}break;case 3:this._executeHandlers[s]?this._executeHandlers[s]():this._executeHandlerFb(s),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:l,code:s,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let c=this._csiHandlers[this._collect<<8|s],a=c?c.length-1:-1;for(;a>=0&&(o=c[a](this._params),o!==!0);a--)if(o instanceof Promise)return this._preserveStack(3,c,a,r,l),o;a<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++l<t&&(s=e[l])>47&&s<60);l--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let u=this._escHandlers[this._collect<<8|s],d=u?u.length-1:-1;for(;d>=0&&(o=u[d](),o!==!0);d--)if(o instanceof Promise)return this._preserveStack(4,u,d,r,l),o;d<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let _=l+1;;++_)if(_>=t||(s=e[_])===24||s===26||s===27||s>127&&s<Ot){this._dcsParser.put(e,l,_),l=_-1;break}break;case 14:if(o=this._dcsParser.unhook(s!==24&&s!==26),o)return this._preserveStack(6,[],0,r,l),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let _=l+1;;_++)if(_>=t||(s=e[_])<32||s>127&&s<Ot){this._oscParser.put(e,l,_),l=_-1;break}break;case 6:if(o=this._oscParser.end(s!==24&&s!==26),o)return this._preserveStack(5,[],0,r,l),o;s===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=r&15}}},dp=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,up=/^[\da-f]+$/;function Il(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let i=dp.exec(t);if(i){let s=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/s*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/s*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/s*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),up.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,s=[0,0,0];for(let r=0;r<3;++r){let n=parseInt(t.slice(i*r,i*r+i),16);s[r]=i===1?n<<4:i===2?n:i===3?n>>4:n>>8}return s}}function In(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function fp(e,t=16){let[i,s,r]=e;return`rgb:${In(i,t)}/${In(s,t)}/${In(r,t)}`}var pp={"(":0,")":1,"*":2,"+":3,"-":1,".":2},pi=131072,Ol=10;function Nl(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Fl=5e3,Hl=0,_p=class extends ve{constructor(e,t,i,s,r,n,o,l,c=new hp){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=l,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new ld,this._utf8Decoder=new cd,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Je.clone(),this._eraseAttrDataInternal=Je.clone(),this._onRequestBell=this._register(new N),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new N),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new N),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new N),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new N),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new N),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new N),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new N),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new N),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new N),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new N),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new N),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new N),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Co(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(a=>this._activeBuffer=a.activeBuffer)),this._parser.setCsiHandlerFallback((a,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(a),params:u.toArray()})}),this._parser.setEscHandlerFallback(a=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(a)})}),this._parser.setExecuteHandlerFallback(a=>{this._logService.debug("Unknown EXECUTE code: ",{code:a})}),this._parser.setOscHandlerFallback((a,u,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:a,action:u,data:d})}),this._parser.setDcsHandlerFallback((a,u,d)=>{u==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(a),action:u,payload:d})}),this._parser.setPrintHandler((a,u,d)=>this.print(a,u,d)),this._parser.registerCsiHandler({final:"@"},a=>this.insertChars(a)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},a=>this.scrollLeft(a)),this._parser.registerCsiHandler({final:"A"},a=>this.cursorUp(a)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},a=>this.scrollRight(a)),this._parser.registerCsiHandler({final:"B"},a=>this.cursorDown(a)),this._parser.registerCsiHandler({final:"C"},a=>this.cursorForward(a)),this._parser.registerCsiHandler({final:"D"},a=>this.cursorBackward(a)),this._parser.registerCsiHandler({final:"E"},a=>this.cursorNextLine(a)),this._parser.registerCsiHandler({final:"F"},a=>this.cursorPrecedingLine(a)),this._parser.registerCsiHandler({final:"G"},a=>this.cursorCharAbsolute(a)),this._parser.registerCsiHandler({final:"H"},a=>this.cursorPosition(a)),this._parser.registerCsiHandler({final:"I"},a=>this.cursorForwardTab(a)),this._parser.registerCsiHandler({final:"J"},a=>this.eraseInDisplay(a,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},a=>this.eraseInDisplay(a,!0)),this._parser.registerCsiHandler({final:"K"},a=>this.eraseInLine(a,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},a=>this.eraseInLine(a,!0)),this._parser.registerCsiHandler({final:"L"},a=>this.insertLines(a)),this._parser.registerCsiHandler({final:"M"},a=>this.deleteLines(a)),this._parser.registerCsiHandler({final:"P"},a=>this.deleteChars(a)),this._parser.registerCsiHandler({final:"S"},a=>this.scrollUp(a)),this._parser.registerCsiHandler({final:"T"},a=>this.scrollDown(a)),this._parser.registerCsiHandler({final:"X"},a=>this.eraseChars(a)),this._parser.registerCsiHandler({final:"Z"},a=>this.cursorBackwardTab(a)),this._parser.registerCsiHandler({final:"`"},a=>this.charPosAbsolute(a)),this._parser.registerCsiHandler({final:"a"},a=>this.hPositionRelative(a)),this._parser.registerCsiHandler({final:"b"},a=>this.repeatPrecedingCharacter(a)),this._parser.registerCsiHandler({final:"c"},a=>this.sendDeviceAttributesPrimary(a)),this._parser.registerCsiHandler({prefix:">",final:"c"},a=>this.sendDeviceAttributesSecondary(a)),this._parser.registerCsiHandler({final:"d"},a=>this.linePosAbsolute(a)),this._parser.registerCsiHandler({final:"e"},a=>this.vPositionRelative(a)),this._parser.registerCsiHandler({final:"f"},a=>this.hVPosition(a)),this._parser.registerCsiHandler({final:"g"},a=>this.tabClear(a)),this._parser.registerCsiHandler({final:"h"},a=>this.setMode(a)),this._parser.registerCsiHandler({prefix:"?",final:"h"},a=>this.setModePrivate(a)),this._parser.registerCsiHandler({final:"l"},a=>this.resetMode(a)),this._parser.registerCsiHandler({prefix:"?",final:"l"},a=>this.resetModePrivate(a)),this._parser.registerCsiHandler({final:"m"},a=>this.charAttributes(a)),this._parser.registerCsiHandler({final:"n"},a=>this.deviceStatus(a)),this._parser.registerCsiHandler({prefix:"?",final:"n"},a=>this.deviceStatusPrivate(a)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},a=>this.softReset(a)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},a=>this.setCursorStyle(a)),this._parser.registerCsiHandler({final:"r"},a=>this.setScrollRegion(a)),this._parser.registerCsiHandler({final:"s"},a=>this.saveCursor(a)),this._parser.registerCsiHandler({final:"t"},a=>this.windowOptions(a)),this._parser.registerCsiHandler({final:"u"},a=>this.restoreCursor(a)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},a=>this.insertColumns(a)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},a=>this.deleteColumns(a)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},a=>this.selectProtected(a)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},a=>this.requestMode(a,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},a=>this.requestMode(a,!1)),this._parser.setExecuteHandler(b.BEL,()=>this.bell()),this._parser.setExecuteHandler(b.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(b.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(b.BS,()=>this.backspace()),this._parser.setExecuteHandler(b.HT,()=>this.tab()),this._parser.setExecuteHandler(b.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(b.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Rs.IND,()=>this.index()),this._parser.setExecuteHandler(Rs.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Rs.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Tt(a=>(this.setTitle(a),this.setIconName(a),!0))),this._parser.registerOscHandler(1,new Tt(a=>this.setIconName(a))),this._parser.registerOscHandler(2,new Tt(a=>this.setTitle(a))),this._parser.registerOscHandler(4,new Tt(a=>this.setOrReportIndexedColor(a))),this._parser.registerOscHandler(8,new Tt(a=>this.setHyperlink(a))),this._parser.registerOscHandler(10,new Tt(a=>this.setOrReportFgColor(a))),this._parser.registerOscHandler(11,new Tt(a=>this.setOrReportBgColor(a))),this._parser.registerOscHandler(12,new Tt(a=>this.setOrReportCursorColor(a))),this._parser.registerOscHandler(104,new Tt(a=>this.restoreIndexedColor(a))),this._parser.registerOscHandler(110,new Tt(a=>this.restoreFgColor(a))),this._parser.registerOscHandler(111,new Tt(a=>this.restoreBgColor(a))),this._parser.registerOscHandler(112,new Tt(a=>this.restoreCursorColor(a))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let a in st)this._parser.registerEscHandler({intermediates:"(",final:a},()=>this.selectCharset("("+a)),this._parser.registerEscHandler({intermediates:")",final:a},()=>this.selectCharset(")"+a)),this._parser.registerEscHandler({intermediates:"*",final:a},()=>this.selectCharset("*"+a)),this._parser.registerEscHandler({intermediates:"+",final:a},()=>this.selectCharset("+"+a)),this._parser.registerEscHandler({intermediates:"-",final:a},()=>this.selectCharset("-"+a)),this._parser.registerEscHandler({intermediates:".",final:a},()=>this.selectCharset("."+a)),this._parser.registerEscHandler({intermediates:"/",final:a},()=>this.selectCharset("/"+a));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(a=>(this._logService.error("Parsing error: ",a),a)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Pl((a,u)=>this.requestStatusString(a,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Fl))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Fl} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>pi&&(n=this._parseStack.position+pi)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,a=>String.fromCharCode(a)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(a=>a.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<pi&&(this._parseBuffer=new Uint32Array(Math.min(e.length,pi))),o||this._dirtyRowTracker.clearRange(),e.length>pi)for(let a=n;a<e.length;a+=pi){let u=a+pi<e.length?a+pi:e.length,d=typeof e=="string"?this._stringDecoder.decode(e.substring(a,u),this._parseBuffer):this._utf8Decoder.decode(e.subarray(a,u),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,d))return this._preserveStack(s,r,d,a),this._logSlowResolvingAsync(i),i}else if(!o){let a=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,a))return this._preserveStack(s,r,a,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let l=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(l,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,l=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,a=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let _=this._parser.precedingJoinState;for(let m=t;m<i;++m){if(s=e[m],s<127&&n){let x=n[String.fromCharCode(s)];x&&(s=x.charCodeAt(0))}let p=this._unicodeService.charProperties(s,_);r=Bi.extractWidth(p);let g=Bi.extractShouldJoin(p),y=g?Bi.extractWidth(_):0;if(_=p,o&&this._onA11yChar.fire(_i(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-y>l){if(c){let x=d,q=this._activeBuffer.x-y;for(this._activeBuffer.x=y,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),y>0&&d instanceof ws&&d.copyCellsFrom(x,q,0,y,!1);q<l;)x.setCellFromCodepoint(q++,0,1,u)}else if(this._activeBuffer.x=l-1,r===2)continue}if(g&&this._activeBuffer.x){let x=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-x,s,r);for(let q=r-y;--q>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(a&&(d.insertCells(this._activeBuffer.x,r-y,this._activeBuffer.getNullCell(u)),d.getWidth(l-1)===2&&d.setCellFromCodepoint(l-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,s,r,u),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=_,this._activeBuffer.x<l&&i-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Nl(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Pl(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Tt(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+i)?.getTrimmedLength(););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Je));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);s.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let i=e.params[0]||1,s=Bi.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),l=0;for(let a=0;a<n.length;){let u=n.codePointAt(a)||0;o[l++]=u,a+=u>65535?2:1}let c=l;for(let a=1;a<i;++a)o.copyWithin(c,0,l),c+=l;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(b.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(b.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(b.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(b.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(b.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Ai),this._charsetService.setgCharset(1,Ai),this._charsetService.setgCharset(2,Ai),this._charsetService.setgCharset(3,Ai);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let i;(g=>(g[g.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",g[g.SET=1]="SET",g[g.RESET=2]="RESET",g[g.PERMANENTLY_SET=3]="PERMANENTLY_SET",g[g.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(i||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:l,cols:c}=this._bufferService,{active:a,alt:u}=l,d=this._optionsService.rawOptions,_=(g,y)=>(o.triggerDataEvent(`${b.ESC}[${t?"":"?"}${g};${y}$y`),!0),m=g=>g?1:2,p=e.params[0];return t?p===2?_(p,4):p===4?_(p,m(o.modes.insertMode)):p===12?_(p,3):p===20?_(p,m(d.convertEol)):_(p,0):p===1?_(p,m(s.applicationCursorKeys)):p===3?_(p,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):p===6?_(p,m(s.origin)):p===7?_(p,m(s.wraparound)):p===8?_(p,3):p===9?_(p,m(r==="X10")):p===12?_(p,m(d.cursorBlink)):p===25?_(p,m(!o.isCursorHidden)):p===45?_(p,m(s.reverseWraparound)):p===66?_(p,m(s.applicationKeypad)):p===67?_(p,4):p===1e3?_(p,m(r==="VT200")):p===1002?_(p,m(r==="DRAG")):p===1003?_(p,m(r==="ANY")):p===1004?_(p,m(s.sendFocus)):p===1005?_(p,4):p===1006?_(p,m(n==="SGR")):p===1015?_(p,4):p===1016?_(p,m(n==="SGR_PIXELS")):p===1048?_(p,1):p===47||p===1047||p===1049?_(p,m(a===u)):p===2004?_(p,m(s.bracketedPasteMode)):p===2026?_(p,m(s.synchronizedOutput)):_(p,0)}_updateAttrColor(e,t,i,s,r){return t===2?(e|=50331648,e&=-16777216,e|=Ms.fromColorRGB([i,s,r])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),l=0;do s[1]===5&&(r=1),s[n+l+1+r]=o[l];while(++l<o.length&&l+n+1+r<s.length);break}if(s[1]===5&&n+r>=2||s[1]===2&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)s[o]===-1&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Je.fg,e.bg=Je.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let r=0;r<t;r++)i=e.params[r],i>=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Je.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Je.bg&16777215):i===38||i===48||i===58?r+=this._extractColor(e,r,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Je.fg&16777215,s.bg&=-67108864,s.bg|=Je.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${b.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[?${t};${i}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Je.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Nl(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${b.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Ol&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Ol&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),r=i.shift();if(/^\d+$/.exec(s)){let n=parseInt(s);if(Wl(n))if(r==="?")t.push({type:0,index:n});else{let o=Il(r);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,r=i.findIndex(n=>n.startsWith("id="));return r!==-1&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Il(i[s]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s<i.length;++s)if(/^\d+$/.exec(i[s])){let r=parseInt(i[s]);Wl(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Ai),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(pp[e[0]],st[e[1]]||Ai),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Je.clone(),this._eraseAttrDataInternal=Je.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Nt;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=o=>(this._coreService.triggerDataEvent(`${b.ESC}${o}${b.ESC}\\`),!0),s=this._bufferService.buffer,r=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Co=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Hl=e,e=t,t=Hl),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Co=ze([U(0,St)],Co);function Wl(e){return 0<=e&&e<256}var mp=5e7,zl=12,gp=50,vp=class extends ve{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new N),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>mp)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],r=this._action(s,t);if(r){let o=l=>performance.now()-i>=zl?setTimeout(()=>this._innerWrite(0,l)):this._innerWrite(i,l);r.catch(l=>(queueMicrotask(()=>{throw l}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=zl)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>gp&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},xo=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let l=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[l]};return l.onDispose(()=>this._removeMarkerFromLink(c,l)),this._dataByLinkId.set(c.id,c),c.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};xo=ze([U(0,St)],xo);var $l=!1,yp=class extends ve{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Gi),this._onBinary=this._register(new N),this.onBinary=this._onBinary.event,this._onData=this._register(new N),this.onData=this._onData.event,this._onLineFeed=this._register(new N),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new N),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new N),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new N),this._instantiationService=new $f,this.optionsService=this._register(new Qf(e)),this._instantiationService.setService(bt,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(yo)),this._instantiationService.setService(St,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(vo)),this._instantiationService.setService(tc,this._logService),this.coreService=this._register(this._instantiationService.createInstance(So)),this._instantiationService.setService(Oi,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bo)),this._instantiationService.setService(ec,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Bi)),this._instantiationService.setService(fd,this.unicodeService),this._charsetService=this._instantiationService.createInstance(rp),this._instantiationService.setService(ud,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(xo),this._instantiationService.setService(ic,this._oscLinkService),this._inputHandler=this._register(new _p(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(ht.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(ht.forward(this._bufferService.onResize,this._onResize)),this._register(ht.forward(this.coreService.onData,this._onData)),this._register(ht.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new vp((t,i)=>this._inputHandler.parse(t,i))),this._register(ht.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new N),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!$l&&(this._logService.warn("writeSync is unreliable and will be removed soon."),$l=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Hc),t=Math.max(t,Wc),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ml.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ml(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Be(()=>{for(let t of e)t.dispose()})}}},Sp={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function bp(e,t,i,s){let r={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?r.key=b.ESC+"OA":r.key=b.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?r.key=b.ESC+"OD":r.key=b.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?r.key=b.ESC+"OC":r.key=b.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?r.key=b.ESC+"OB":r.key=b.ESC+"[B");break;case 8:r.key=e.ctrlKey?"\b":b.DEL,e.altKey&&(r.key=b.ESC+r.key);break;case 9:if(e.shiftKey){r.key=b.ESC+"[Z";break}r.key=b.HT,r.cancel=!0;break;case 13:r.key=e.altKey?b.ESC+b.CR:b.CR,r.cancel=!0;break;case 27:r.key=b.ESC,e.altKey&&(r.key=b.ESC+b.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"D":t?r.key=b.ESC+"OD":r.key=b.ESC+"[D";break;case 39:if(e.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"C":t?r.key=b.ESC+"OC":r.key=b.ESC+"[C";break;case 38:if(e.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"A":t?r.key=b.ESC+"OA":r.key=b.ESC+"[A";break;case 40:if(e.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"B":t?r.key=b.ESC+"OB":r.key=b.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=b.ESC+"[2~");break;case 46:n?r.key=b.ESC+"[3;"+(n+1)+"~":r.key=b.ESC+"[3~";break;case 36:n?r.key=b.ESC+"[1;"+(n+1)+"H":t?r.key=b.ESC+"OH":r.key=b.ESC+"[H";break;case 35:n?r.key=b.ESC+"[1;"+(n+1)+"F":t?r.key=b.ESC+"OF":r.key=b.ESC+"[F";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=b.ESC+"[5;"+(n+1)+"~":r.key=b.ESC+"[5~";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=b.ESC+"[6;"+(n+1)+"~":r.key=b.ESC+"[6~";break;case 112:n?r.key=b.ESC+"[1;"+(n+1)+"P":r.key=b.ESC+"OP";break;case 113:n?r.key=b.ESC+"[1;"+(n+1)+"Q":r.key=b.ESC+"OQ";break;case 114:n?r.key=b.ESC+"[1;"+(n+1)+"R":r.key=b.ESC+"OR";break;case 115:n?r.key=b.ESC+"[1;"+(n+1)+"S":r.key=b.ESC+"OS";break;case 116:n?r.key=b.ESC+"[15;"+(n+1)+"~":r.key=b.ESC+"[15~";break;case 117:n?r.key=b.ESC+"[17;"+(n+1)+"~":r.key=b.ESC+"[17~";break;case 118:n?r.key=b.ESC+"[18;"+(n+1)+"~":r.key=b.ESC+"[18~";break;case 119:n?r.key=b.ESC+"[19;"+(n+1)+"~":r.key=b.ESC+"[19~";break;case 120:n?r.key=b.ESC+"[20;"+(n+1)+"~":r.key=b.ESC+"[20~";break;case 121:n?r.key=b.ESC+"[21;"+(n+1)+"~":r.key=b.ESC+"[21~";break;case 122:n?r.key=b.ESC+"[23;"+(n+1)+"~":r.key=b.ESC+"[23~";break;case 123:n?r.key=b.ESC+"[24;"+(n+1)+"~":r.key=b.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=b.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=b.DEL:e.keyCode===219?r.key=b.ESC:e.keyCode===220?r.key=b.FS:e.keyCode===221&&(r.key=b.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let o=Sp[e.keyCode]?.[e.shiftKey?1:0];if(o)r.key=b.ESC+o;else if(e.keyCode>=65&&e.keyCode<=90){let l=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(l);e.shiftKey&&(c=c.toUpperCase()),r.key=b.ESC+c}else if(e.keyCode===32)r.key=b.ESC+(e.ctrlKey?b.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let l=e.code.slice(3,4);e.shiftKey||(l=l.toLowerCase()),r.key=b.ESC+l,r.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(r.key=b.US),e.key==="@"&&(r.key=b.NUL));break}return r}var je=0,wp=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Dr,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Dr,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,n)=>this._getKey(r)-this._getKey(n)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(je=this._search(t),je===-1)||this._getKey(this._array[je])!==t)return!1;do if(this._array[je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(je),!0;while(++je<this._array.length&&this._getKey(this._array[je])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((r,n)=>r-n),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(je=this._search(e),!(je<0||je>=this._array.length)&&this._getKey(this._array[je])===e))do yield this._array[je];while(++je<this._array.length&&this._getKey(this._array[je])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(je=this._search(e),!(je<0||je>=this._array.length)&&this._getKey(this._array[je])===e))do t(this._array[je]);while(++je<this._array.length&&this._getKey(this._array[je])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else if(r<e)t=s+1;else{for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},On=0,Kl=0,Cp=class extends ve{constructor(){super(),this._decorations=new wp(e=>e?.marker.line),this._onDecorationRegistered=this._register(new N),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new N),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Be(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new xp(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,r=>{On=r.options.x??0,Kl=On+(r.options.width??1),e>=On&&e<Kl&&(!i||(r.options.layer??"bottom")===i)&&s(r)})}},xp=class extends gi{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new N),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new N),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Pe.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Pe.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},kp=1e3,Ep=class{constructor(e,t=kp){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=s-this._lastRefreshMs,n=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Ul=20,ql=!1,Ar=class extends ve{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Ep(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");ql?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=r.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(r.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(r.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
55
|
+
`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(oe(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Be(()=>{ql?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Ul+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
56
|
+
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Ul+1&&(this._liveRegion.textContent+=Fn.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let n=i.lines.get(i.ydisp+r),o=[],l=n?.translateToString(!0,void 0,void 0,o)||"",c=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(l.length===0?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=l,this._rowColumns.set(a,o)),a.setAttribute("aria-posinset",c),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],r=i.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(r===n||e.relatedTarget!==s)return;let o,l;if(t===0?(o=i,l=this._rowElements.pop(),this._rowContainer.removeChild(l)):(o=this._rowElements.shift(),l=i,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),l.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;let r=({node:l,offset:c})=>{let a=l instanceof Text?l.parentNode:l,u=parseInt(a?.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(a);if(!d)return console.warn("columns is null. Race condition?"),null;let _=c<d.length?d[c]:d.slice(-1)[0]+1;return _>=this._terminal.cols&&(++u,_=0),{row:u,column:_}},n=r(t),o=r(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform="";let t=e.getBoundingClientRect().width,i=this._rowColumns.get(e)?.slice(-1)?.[0];if(!i)return;let s=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};Ar=ze([U(1,Eo),U(2,ri),U(3,ni)],Ar);var ko=class extends ve{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new N),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new N),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Be(()=>{Pi(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(oe(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(oe(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(oe(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(oe(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s<i.length;s++){let r=i[s];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(s=>{s?.forEach(r=>{r.link.dispose&&r.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[s,r]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(s)&&(i=this._checkLinkProviderResult(s,e,i)):r.provideLinks(e.y,n=>{if(this._isMouseOut)return;let o=n?.map(l=>({link:l}));this._activeProviderReplies?.set(s,o),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let n=0;n<r.length;n++){let o=r[n],l=o.link.range.start.y<e?0:o.link.range.start.x,c=o.link.range.end.y>e?this._bufferService.cols:o.link.range.end.x;for(let a=l;a<=c;a++){if(i.has(a)){r.splice(n--,1);break}i.add(a)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),r=!1;for(let n=0;n<e;n++)(!this._activeProviderReplies.has(n)||this._activeProviderReplies.get(n))&&(r=!0);if(!r&&s){let n=s.find(o=>this._linkAtPosition(o.link,t));n&&(i=!0,this._handleNewLink(n))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let n=0;n<this._activeProviderReplies.size;n++){let o=this._activeProviderReplies.get(n)?.find(l=>this._linkAtPosition(l.link,t));if(o){i=!0,this._handleNewLink(o);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Rp(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Pi(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:i=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:i=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(s,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};ko=ze([U(1,Ro),U(2,ni),U(3,St),U(4,rc)],ko);function Rp(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var Lp=class extends yp{constructor(e={}){super(e),this._linkifier=this._register(new Gi),this.browser=Lc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Gi),this._onCursorMove=this._register(new N),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new N),this.onKey=this._onKey.event,this._onRender=this._register(new N),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new N),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new N),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new N),this.onBell=this._onBell.event,this._onFocus=this._register(new N),this._onBlur=this._register(new N),this._onA11yCharEmitter=this._register(new N),this._onA11yTabEmitter=this._register(new N),this._onWillOpen=this._register(new N),this._setup(),this._decorationService=this._instantiationService.createInstance(Cp),this._instantiationService.setService(Ps,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(mf),this._instantiationService.setService(rc,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Wn)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(ht.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ht.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ht.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ht.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Be(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let r=Ae.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${b.ESC}]${s};${fp(r)}${lo.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=Ye.toColor(...t.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=Ye.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ar,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,l=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=l+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(oe(this.element,"copy",t=>{this.hasSelection()&&od(t,this._selectionService)}));let e=t=>ad(t,this.textarea,this.coreService,this.optionsService);this._register(oe(this.textarea,"paste",e)),this._register(oe(this.element,"paste",e)),Tc?this._register(oe(this.element,"mousedown",t=>{t.button===2&&Ka(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(oe(this.element,"contextmenu",t=>{Ka(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Io&&this._register(oe(this.element,"auxclick",t=>{t.button===1&&Gl(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(oe(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(oe(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(oe(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(oe(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(oe(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(oe(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(oe(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(oe(this.screenElement,"mousemove",r=>this.updateCursorStyle(r))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Nn.get()),Bc||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(pf,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ri,this._coreBrowserService),this._register(oe(this.textarea,"focus",r=>this._handleTextAreaFocus(r))),this._register(oe(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(fo,this._document,this._helperContainer),this._instantiationService.setService(Mr,this._charSizeService),this._themeService=this._instantiationService.createInstance(go),this._instantiationService.setService(Xi,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Lr),this._instantiationService.setService(sc,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(_o,this.rows,this.screenElement)),this._instantiationService.setService(ni,this._renderService),this._register(this._renderService.onRenderedViewportChange(r=>this._onRender.fire(r))),this.onResize(r=>this._renderService.resize(r.cols,r.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(co,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(po),this._instantiationService.setService(Ro,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(ko,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(oo,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(r=>{super.scrollLines(r,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(mo,this.element,this.screenElement,s)),this._instantiationService.setService(_d,this._selectionService),this._register(this._selectionService.onRequestScrollLines(r=>this.scrollLines(r.amount,r.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(r=>this._renderService.handleSelectionChanged(r.start,r.end,r.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(r=>{this.textarea.value=r,this.textarea.focus(),this.textarea.select()})),this._register(ht.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ao,this.screenElement)),this._register(oe(this.element,"mousedown",r=>this._selectionService.handleMouseDown(r))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ar,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",r=>this._handleScreenReaderModeOptionChange(r))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Rr,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",r=>{!this._overviewRulerRenderer&&r&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Rr,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(uo,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(n){let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let l,c;switch(n.overrideType||n.type){case"mousemove":c=32,n.buttons===void 0?(l=3,n.button!==void 0&&(l=n.button<3?n.button:3)):l=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":c=0,l=n.button<3?n.button:3;break;case"mousedown":c=1,l=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let a=n.deltaY;if(a===0||e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=a<0?0:1,l=4;break;default:return!1}return c===void 0||l===void 0||l>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:l,action:c,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),n&16?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),n&2?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),n&4?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(oe(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(n)})),this._register(oe(t,"wheel",n=>{if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(n,!0);let o=b.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(o,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Yl(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=bp(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===b.ETX||i.key===b.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Tp(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(Je));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(b.ESC+"[I"):this.coreService.triggerDataEvent(b.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${b.ESC}[4;${i};${t}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${b.ESC}[6;${r};${s}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Tp(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Dp=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Ap=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Nt)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Vl=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Ap(t)}getNullCell(){return new Nt}},Bp=class extends ve{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new N),this.onBufferChange=this._onBufferChange.event,this._normal=new Vl(this._core.buffers.normal,"normal"),this._alternate=new Vl(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Mp=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},Pp=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},Ip=["cols","rows"],Gt=0,$c=class extends ve{constructor(e){super(),this._core=this._register(new Lp(e)),this._addonManager=this._register(new Dp),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,r)=>{this._checkReadonlyOptions(s),this._core.options[s]=r};for(let s in this._core.options){let r={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,r)}}_checkReadonlyOptions(e){if(Ip.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Mp(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Pp(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new Bp(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
57
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Nn.get()},set promptLabel(e){Nn.set(e)},get tooMuchOutput(){return Fn.get()},set tooMuchOutput(e){Fn.set(e)}}}_verifyIntegers(...e){for(Gt of e)if(Gt===1/0||isNaN(Gt)||Gt%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Gt of e)if(Gt&&(Gt===1/0||isNaN(Gt)||Gt%1!==0||Gt<0))throw new Error("This API only accepts positive integers")}};/**
|
|
58
58
|
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
|
|
59
59
|
* @license MIT
|
|
60
60
|
*
|
|
@@ -65,7 +65,7 @@ ${u.join(`
|
|
|
65
65
|
* Fabrice Bellard's javascript vt100 for jslinux:
|
|
66
66
|
* http://bellard.org/jslinux/
|
|
67
67
|
* Copyright (c) 2011 Fabrice Bellard
|
|
68
|
-
*/var
|
|
68
|
+
*/var Op=2,Np=1,Kc=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),r=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),o={top:parseInt(n.getPropertyValue("padding-top")),bottom:parseInt(n.getPropertyValue("padding-bottom")),right:parseInt(n.getPropertyValue("padding-right")),left:parseInt(n.getPropertyValue("padding-left"))},l=o.top+o.bottom,c=o.right+o.left,a=s-l,u=r-c-t;return{cols:Math.max(Op,Math.floor(u/e.css.cell.width)),rows:Math.max(Np,Math.floor(a/e.css.cell.height))}}};var Uc=`/**
|
|
69
69
|
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
|
|
70
70
|
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
|
71
71
|
* https://github.com/chjj/term.js
|
|
@@ -350,8 +350,8 @@ ${u.join(`
|
|
|
350
350
|
.xterm .xterm-scrollable-element > .shadow.top.left {
|
|
351
351
|
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
|
|
352
352
|
}
|
|
353
|
-
`;var
|
|
354
|
-
`),!0)}var f={labelPrimary:"var(--dsw-alias-label-primary)",labelSecondary:"var(--dsw-alias-label-secondary)",labelTertiary:"var(--dsw-alias-label-tertiary)",labelForeground:"var(--dsw-alias-label-primary-foreground)",bgBase:"var(--dsw-alias-bg-base)",bgLayer1:"var(--dsw-alias-bg-layer-1)",bgLayer2:"var(--dsw-alias-bg-layer-2)",bgLayer3:"var(--dsw-alias-bg-layer-3)",bgOverlay:"var(--dsw-alias-bg-overlay)",borderL1:"var(--dsw-alias-border-l1)",borderL2:"var(--dsw-alias-border-l2)",borderL3:"var(--dsw-alias-border-l3)",brand:"var(--dsw-alias-brand-primary)",primaryFill:"var(--dsw-alias-button-primary-fill)",primaryHover:"var(--dsw-alias-button-primary-hover)",hover:"var(--dsw-alias-interactive-bg-hover)",hoverDanger:"var(--dsw-alias-interactive-bg-hover-danger)",active:"var(--dsw-alias-interactive-bg-active)",danger:"var(--dsw-alias-state-error-primary)",success:"var(--dsw-alias-state-success-primary)",warn:"var(--dsw-alias-state-warn-primary)",warnLabel:"var(--dsw-alias-state-warn-label)",idle:"var(--dsw-alias-state-idle-primary)",toastBg:"var(--dsw-alias-toast-bg)",toastLabel:"var(--dsw-alias-toast-label)",radiusSm:"var(--dsw-radius-sm)",radiusMd:"var(--dsw-radius-md)",focusRing:"var(--dsw-focus-ring-color)",elevationSoft:"var(--dsw-elevation-soft)",elevationPanel:"var(--dsw-elevation-panel)",fontFamily:"var(--dsw-font-family)"},c={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,minWidth:0,boxSizing:"border-box",color:f.labelPrimary,background:"transparent",fontFamily:f.fontFamily,fontSize:12,lineHeight:1.4,position:"relative",overflow:"hidden"},rail:{display:"flex",alignItems:"center",gap:6,flex:"none",padding:"5px 8px",borderBottom:`0.5px solid ${f.borderL2}`,overflowX:"auto",overflowY:"hidden",scrollbarWidth:"thin"},railChip:{position:"relative",display:"inline-flex",alignItems:"center",gap:6,flex:"none",maxWidth:190,height:34,padding:"0 4px 0 10px",border:"0.5px solid transparent",borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:13,lineHeight:1,cursor:"pointer",outline:"none",userSelect:"none"},railChipActive:{background:f.bgLayer3,borderColor:f.brand,color:f.labelPrimary,boxShadow:`inset 3px 0 0 ${f.brand}`},railChipHover:{background:f.hover,color:f.labelPrimary},railTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},railTitleDim:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,opacity:.7},transportBadge:{flex:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"1px 4px",borderRadius:3,border:"0.5px solid transparent",fontSize:9,lineHeight:"12px",letterSpacing:"0.04em",textTransform:"uppercase",fontWeight:600},transportBadgeSsh:{color:f.brand,borderColor:f.brand,background:f.bgLayer2},transportBadgeTelnet:{color:f.warn,borderColor:f.warn,background:f.bgLayer2},railTag:{flex:"none",fontSize:11,letterSpacing:"0.02em",color:f.labelTertiary,textTransform:"uppercase"},railDotButton:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:22,height:22,padding:0,border:0,borderRadius:4,background:"transparent",color:f.labelTertiary,font:"inherit",fontSize:13,lineHeight:1,cursor:"pointer",outline:"none"},railSpacer:{flex:"1 1 auto",minWidth:6},railAdd:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:32,height:32,padding:0,marginLeft:"auto",border:`0.5px dashed ${f.borderL2}`,borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:14,lineHeight:1,cursor:"pointer",outline:"none"},controlBar:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,flex:"none",padding:"6px 8px",borderBottom:`0.5px solid ${f.borderL2}`,minHeight:44},controlSpacer:{flex:1,minWidth:0},railConfirmWrap:{flex:"none",padding:"0 8px 6px"},lockChip:{display:"inline-flex",alignItems:"center",gap:5,flex:"none",height:30,padding:"0 10px",borderRadius:999,border:`0.5px solid ${f.borderL2}`,background:f.bgLayer1,fontSize:12,lineHeight:1,whiteSpace:"nowrap"},lockDot:{flex:"none",width:6,height:6,borderRadius:"50%"},pane:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,position:"relative"},termWrap:{display:"flex",flex:1,minHeight:0,minWidth:0,position:"relative",padding:"4px 4px 2px 6px"},statusBar:{display:"flex",alignItems:"center",gap:8,flex:"none",padding:"4px 10px",borderTop:`0.5px solid ${f.borderL2}`,color:f.labelTertiary,fontSize:12,lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden"},quickBar:{display:"flex",flexDirection:"column",gap:4,flex:"none",padding:"5px 8px",borderTop:`0.5px solid ${f.borderL2}`,background:f.bgLayer1},quickBarHead:{display:"flex",alignItems:"center",gap:6,flex:"none",minHeight:26},quickBarTitle:{flex:"none",fontSize:11,letterSpacing:"0.02em",color:f.labelTertiary,textTransform:"uppercase"},quickBarRow:{display:"flex",alignItems:"center",gap:8,flex:"none",overflowX:"auto",overflowY:"hidden",paddingBottom:2,scrollbarWidth:"thin"},quickGroup:{display:"inline-flex",alignItems:"center",gap:4,flex:"none"},quickFolder:{flex:"none",padding:"0 2px",fontSize:10,color:f.labelTertiary,textTransform:"uppercase",letterSpacing:"0.02em"},quickChip:{display:"inline-flex",alignItems:"center",flex:"none",maxWidth:160,height:26,padding:"0 9px",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.labelPrimary,font:"inherit",fontSize:12,lineHeight:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",outline:"none"},quickChipBusy:{color:f.labelTertiary,cursor:"default"},quickBarCollapsed:{display:"flex",alignItems:"center",flex:"none",padding:"3px 8px",borderTop:`0.5px solid ${f.borderL2}`},quickSheetGroup:{display:"flex",flexDirection:"column",gap:2,flex:"none"},statusItem:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},banner:{display:"flex",alignItems:"center",gap:8,flex:"none",padding:"7px 10px",borderBottom:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.warn}`,background:f.bgLayer2,color:f.labelPrimary,fontSize:12,lineHeight:1.45},bannerText:{flex:1,minWidth:0},bannerHint:{color:f.labelTertiary,display:"block"},inlineConfirm:{display:"flex",alignItems:"center",gap:8,flex:"none",flexWrap:"wrap",padding:"6px 8px",border:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.danger}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.labelPrimary,fontSize:12,lineHeight:1.4},inlineConfirmText:{flex:"1 1 120px",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},overlay:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:f.bgOverlay,color:f.labelSecondary,textAlign:"center"},overlayCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,maxWidth:340,padding:"14px 16px",borderRadius:f.radiusMd,border:`0.5px solid ${f.borderL2}`,background:f.bgBase,boxShadow:f.elevationSoft,color:f.labelSecondary},overlayTitle:{margin:0,color:f.labelPrimary,fontSize:13,fontWeight:500,lineHeight:1.4,overflowWrap:"anywhere"},overlayDetail:{margin:0,color:f.labelTertiary,fontSize:11,lineHeight:1.5,overflowWrap:"anywhere"},toast:{position:"absolute",top:8,right:8,zIndex:20,maxWidth:"90%",padding:"8px 12px",borderRadius:f.radiusSm,background:f.toastBg,color:f.toastLabel,fontSize:12,lineHeight:1.45,boxShadow:f.elevationSoft,pointerEvents:"none"},stateWrap:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:10,padding:"24px 18px",textAlign:"center",color:f.labelSecondary,overflow:"auto"},stateTitle:{margin:0,color:f.labelPrimary,fontSize:14,fontWeight:500,lineHeight:1.5,maxWidth:"30ch",overflowWrap:"anywhere"},stateDetail:{margin:0,color:f.labelTertiary,fontSize:12,lineHeight:1.55,maxWidth:"40ch",overflowWrap:"anywhere"},form:{display:"flex",flexDirection:"column",flex:1,minHeight:0},formScroll:{display:"flex",flexDirection:"column",gap:10,flex:1,minHeight:0,padding:"12px 12px 6px",overflowY:"auto",scrollbarWidth:"thin"},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{color:f.labelSecondary,fontSize:12,lineHeight:1.3},row:{display:"flex",alignItems:"flex-end",gap:8,minWidth:0},grow:{flex:1,minWidth:0},portField:{flex:"none",width:88},input:{boxSizing:"border-box",width:"100%",height:32,padding:"0 10px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontSize:13,lineHeight:1.3,outline:"none"},textarea:{boxSizing:"border-box",width:"100%",minHeight:96,padding:"8px 10px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontFamily:"monospace",fontSize:12,lineHeight:1.45,resize:"vertical",outline:"none"},select:{boxSizing:"border-box",width:"100%",height:32,padding:"0 8px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontSize:13,outline:"none"},hint:{color:f.labelTertiary,fontSize:11,lineHeight:1.45},formError:{padding:"7px 9px",border:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.danger}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.danger,fontSize:12,lineHeight:1.45,overflowWrap:"anywhere"},formActions:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flex:"none",padding:"10px 12px",borderTop:`0.5px solid ${f.borderL2}`},checkboxRow:{display:"flex",alignItems:"center",gap:8,color:f.labelSecondary,fontSize:12,cursor:"pointer",userSelect:"none"},checkbox:{flex:"none",width:16,height:16,margin:0,accentColor:f.brand,cursor:"pointer"},popover:{position:"absolute",top:"calc(100% + 4px)",right:0,zIndex:30,width:"min(320px, 92vw)",maxHeight:300,display:"flex",flexDirection:"column",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusMd,background:f.bgBase,boxShadow:f.elevationPanel,overflow:"hidden"},popoverHeader:{display:"flex",alignItems:"center",gap:6,flex:"none",padding:"8px 10px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontSize:12,fontWeight:600},auditList:{display:"flex",flexDirection:"column",flex:1,minHeight:0,overflowY:"auto",scrollbarWidth:"thin",padding:"2px 0"},auditRow:{display:"flex",alignItems:"baseline",gap:6,padding:"4px 10px",fontSize:12,lineHeight:1.4,color:f.labelSecondary},auditTime:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},auditBadge:{flex:"none",padding:"0 5px",borderRadius:3,border:`0.5px solid ${f.borderL2}`,color:f.labelSecondary,fontSize:11,lineHeight:"15px"},auditDetail:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelSecondary,fontFamily:"monospace",fontSize:11},auditEmpty:{padding:"12px 8px",textAlign:"center",color:f.labelTertiary,fontSize:11},overlayWindow:{position:"absolute",inset:12,zIndex:30,display:"flex",flexDirection:"column",minWidth:0,minHeight:0,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusMd,background:f.bgLayer1,boxShadow:f.elevationPanel,overflow:"hidden"},overlayWindowHead:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:44,padding:"6px 8px 6px 12px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontSize:13,fontWeight:600},overlayWindowTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},overlayWindowBody:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},sheet:{position:"absolute",inset:0,zIndex:15,display:"flex",flexDirection:"column",minWidth:0,minHeight:0,background:f.bgBase,color:f.labelPrimary,overflow:"hidden"},viewHeader:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:46,padding:"6px 8px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontWeight:600},viewHeaderText:{display:"flex",flexDirection:"column",gap:1,flex:1,minWidth:0},viewHeaderTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelPrimary,fontSize:13,lineHeight:1.3},viewHeaderHint:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,fontSize:11,fontWeight:400,lineHeight:1.35},viewHeaderActions:{display:"flex",alignItems:"center",gap:6,flex:"none"},sheetBody:{display:"flex",flexDirection:"column",gap:9,flex:1,minHeight:0,minWidth:0,padding:"10px 10px 8px",overflow:"hidden"},sheetFooter:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:40,padding:"6px 10px",borderTop:`0.5px solid ${f.borderL2}`,color:f.labelTertiary,fontSize:12,lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden"},sectionTitle:{color:f.labelSecondary,fontSize:12,lineHeight:1.35},filterRow:{display:"flex",alignItems:"flex-end",gap:6,minWidth:0,flex:"none"},listBox:{display:"flex",flexDirection:"column",flex:"none",maxHeight:120,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},listToolbar:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,flex:"none",padding:"0 0 8px",borderBottom:`0.5px solid ${f.borderL2}`,marginBottom:8},listToolbarMeta:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,color:f.labelTertiary},folderBar:{display:"flex",alignItems:"center",gap:8,flex:"none",flexWrap:"wrap"},scriptSplit:{display:"flex",alignItems:"stretch",gap:10,flex:1,minHeight:0,minWidth:0},scriptListCol:{display:"flex",flexDirection:"column",gap:6,flex:"none",width:172,minWidth:130,maxWidth:200,minHeight:0},scriptListScroll:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},scriptRowActive:{background:f.bgLayer3,color:f.labelPrimary,boxShadow:`inset 2px 0 0 ${f.brand}`},newChoicePop:{position:"absolute",bottom:"100%",left:0,zIndex:25,display:"flex",flexDirection:"column",gap:4,minWidth:132,padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgOverlay,boxShadow:f.elevationPanel},newChoiceOption:{justifyContent:"flex-start",width:"100%"},scriptListButtons:{display:"flex",alignItems:"center",gap:4,flex:"none",flexWrap:"wrap"},rowBtnSmall:{height:28,padding:"0 7px",fontSize:11},scriptEditCol:{display:"flex",flexDirection:"column",gap:9,flex:1,minWidth:0,minHeight:0},editorGrow:{display:"flex",flexDirection:"column",flex:"1 1 auto",minHeight:0},editorBody:{flex:"1 1 auto",minHeight:120,resize:"none"},runSection:{display:"flex",flexDirection:"column",gap:7,flex:"none",paddingTop:8,borderTop:`0.5px solid ${f.borderL2}`},resultSummary:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,color:f.labelSecondary},pickList:{display:"flex",flexDirection:"column",gap:4,flex:"none",maxHeight:148,padding:"6px 8px",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},exportBox:{display:"flex",flexDirection:"column",gap:2,flex:"none",padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1},exportRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minWidth:0},exportPath:{flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:11,color:f.labelPrimary},exportMeta:{flex:"none",fontSize:11,color:f.labelTertiary},checkRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:26,cursor:"pointer"},checkLabel:{minWidth:0,fontSize:12,color:f.labelPrimary},pickRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:26,cursor:"pointer"},pickBox:{flex:"none",width:15,height:15,margin:0,accentColor:f.brand,cursor:"pointer"},pickTitle:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,color:f.labelPrimary},pickMeta:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,color:f.labelTertiary},listRow:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:1,flex:"none",width:"100%",padding:"6px 9px",border:0,borderBottom:`0.5px solid ${f.borderL1}`,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1.35,textAlign:"left",cursor:"pointer",outline:"none"},listRowActive:{background:f.bgLayer3,color:f.labelPrimary},listRowTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},listRowMeta:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,fontSize:11,fontVariantNumeric:"tabular-nums"},scrollArea:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},matchRow:{display:"flex",alignItems:"baseline",gap:7,flex:"none",padding:"2px 3px",fontFamily:"monospace",fontSize:11,lineHeight:1.5,color:f.labelPrimary},matchTime:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},matchText:{flex:1,minWidth:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},contextText:{flex:1,minWidth:0,color:f.labelTertiary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},matchHit:{color:f.brand,fontWeight:600},dialectTag:{flex:"none",padding:"0 5px",borderRadius:3,fontSize:10,lineHeight:"14px",color:f.labelTertiary,background:f.bgLayer3},resultBox:{display:"flex",flexDirection:"column",gap:1,flex:1,minHeight:0,padding:"4px 0",overflowY:"auto",scrollbarWidth:"thin"},batchLine:{display:"flex",alignItems:"baseline",gap:5,flex:"none",padding:"2px 7px",fontFamily:"monospace",fontSize:11,lineHeight:1.5,whiteSpace:"nowrap"},batchIndex:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},batchSession:{flex:"none",color:f.labelTertiary},batchText:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",color:f.labelSecondary},batchPath:{flex:"none",color:f.labelTertiary,whiteSpace:"pre",fontVariantNumeric:"tabular-nums"},batchKind:{flex:"none",color:f.labelTertiary},batchSep:{flex:"none",color:f.labelTertiary},actionRow:{display:"flex",alignItems:"center",gap:6,flex:"none",flexWrap:"wrap"},profileList:{display:"flex",flexDirection:"column",gap:6,flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},profileSection:{display:"flex",flexDirection:"column",gap:2,flex:"none",minWidth:0},profileSectionHeader:{display:"flex",alignItems:"baseline",gap:6,flex:"none",padding:"4px 2px 2px",color:f.labelSecondary,fontSize:12,fontWeight:600},profileCount:{color:f.labelTertiary,fontSize:11,fontWeight:400,fontVariantNumeric:"tabular-nums"},profileRow:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:7,flex:"none",minWidth:0,padding:"8px 9px",border:`0.5px solid ${f.borderL1}`,borderRadius:f.radiusSm,background:f.bgLayer1},profileRowHighlight:{borderColor:f.brand,background:f.bgLayer3},profileMain:{display:"flex",flexDirection:"column",gap:2,flex:"none",minWidth:0},profileName:{color:f.labelPrimary,fontSize:13,fontWeight:600,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},profileAddress:{color:f.labelTertiary,fontFamily:"monospace",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},profileBadges:{display:"flex",alignItems:"center",gap:4,flexWrap:"wrap"},badge:{flex:"none",padding:"1px 5px",borderRadius:3,border:`0.5px solid ${f.borderL2}`,color:f.labelSecondary,fontSize:11,lineHeight:"16px"},profileActions:{display:"flex",alignItems:"center",gap:5,flex:"none",flexWrap:"wrap",minWidth:0},rowBtn:{height:30,padding:"0 8px",fontSize:12},inlineRow:{display:"flex",alignItems:"center",gap:6,flex:"none",flexWrap:"wrap",minWidth:0},folderPickerRow:{display:"flex",alignItems:"flex-end",gap:8,flex:"none",minWidth:0},listGroupHeader:{display:"flex",alignItems:"baseline",gap:6,flex:"none",padding:"4px 2px 2px",color:f.labelSecondary,fontSize:11,fontWeight:600},templateRow:{display:"flex",alignItems:"center",gap:6,flex:"none",minWidth:0}};function Pi(e){return e?`inset 0 0 0 1px ${f.focusRing}`:void 0}var Np={background:"#17191d",foreground:"#e6e6e6",cursor:"#e6e6e6",cursorAccent:"#17191d",selectionBackground:"rgba(77, 107, 254, 0.35)",black:"#1f2125",red:"#e5484d",green:"#2fbf71",yellow:"#d9a300",blue:"#4d8bff",magenta:"#c678dd",cyan:"#56b6c2",white:"#d7dae0",brightBlack:"#5c6370",brightRed:"#ff6b70",brightGreen:"#5ad68f",brightYellow:"#f0c040",brightBlue:"#7aa7ff",brightMagenta:"#e39ff6",brightCyan:"#7fd4de",brightWhite:"#ffffff"},Fp=/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]*\)|hsla?\([^)]*\))$/i;function vo(e){if(!(typeof document>"u"||typeof window>"u"))try{let t=window.getComputedStyle(document.documentElement).getPropertyValue(e);if(typeof t!="string")return;let i=t.trim();return!i||i.includes("var(")?void 0:Fp.test(i)?i:void 0}catch{return}}function yo(){let e={...Np},t=vo("--dsw-alias-bg-layer-1")||vo("--dsw-alias-bg-base"),i=vo("--dsw-alias-label-primary");return t&&(e.background=t,e.cursorAccent=t),i&&(e.foreground=i,e.cursor=i),e}var Hp='Consolas, "Cascadia Mono", "SFMono-Regular", Menlo, "Courier New", monospace';function Bh(e){return{allowProposedApi:!0,convertEol:!1,cursorBlink:!0,fontFamily:Hp,fontSize:12,lineHeight:1.18,scrollback:4e3,scrollSensitivity:1.4,theme:yo(),...e}}var Lh=`
|
|
353
|
+
`;var Hp="terminalResetNotice";function Oo(e){let t=Number(e);return!Number.isFinite(t)||t<0?0:Math.trunc(t)}function No(e){return D(e,Hp)}function Fr(e=0){let t=Oo(e);return{get applied(){return t},claim(i){let s=Oo(i);return s<=t?!1:(t=s,!0)},markApplied(i){let s=Oo(i);s>t&&(t=s)}}}function Hr(e,t,i,s){return!e||!s||typeof e.reset!="function"||typeof e.write!="function"||!s.claim(i)?!1:(e.reset(),e.write(No(t)+`\r
|
|
354
|
+
`),!0)}var f={labelPrimary:"var(--dsw-alias-label-primary)",labelSecondary:"var(--dsw-alias-label-secondary)",labelTertiary:"var(--dsw-alias-label-tertiary)",labelForeground:"var(--dsw-alias-label-primary-foreground)",bgBase:"var(--dsw-alias-bg-base)",bgLayer1:"var(--dsw-alias-bg-layer-1)",bgLayer2:"var(--dsw-alias-bg-layer-2)",bgLayer3:"var(--dsw-alias-bg-layer-3)",bgOverlay:"var(--dsw-alias-bg-overlay)",borderL1:"var(--dsw-alias-border-l1)",borderL2:"var(--dsw-alias-border-l2)",borderL3:"var(--dsw-alias-border-l3)",brand:"var(--dsw-alias-brand-primary)",primaryFill:"var(--dsw-alias-button-primary-fill)",primaryHover:"var(--dsw-alias-button-primary-hover)",hover:"var(--dsw-alias-interactive-bg-hover)",hoverDanger:"var(--dsw-alias-interactive-bg-hover-danger)",active:"var(--dsw-alias-interactive-bg-active)",danger:"var(--dsw-alias-state-error-primary)",success:"var(--dsw-alias-state-success-primary)",warn:"var(--dsw-alias-state-warn-primary)",warnLabel:"var(--dsw-alias-state-warn-label)",idle:"var(--dsw-alias-state-idle-primary)",toastBg:"var(--dsw-alias-toast-bg)",toastLabel:"var(--dsw-alias-toast-label)",radiusSm:"var(--dsw-radius-sm)",radiusMd:"var(--dsw-radius-md)",focusRing:"var(--dsw-focus-ring-color)",elevationSoft:"var(--dsw-elevation-soft)",elevationPanel:"var(--dsw-elevation-panel)",fontFamily:"var(--dsw-font-family)"},h={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,minWidth:0,boxSizing:"border-box",color:f.labelPrimary,background:"transparent",fontFamily:f.fontFamily,fontSize:12,lineHeight:1.4,position:"relative",overflow:"hidden"},rail:{display:"flex",alignItems:"center",gap:6,flex:"none",padding:"5px 8px",borderBottom:`0.5px solid ${f.borderL2}`,overflowX:"auto",overflowY:"hidden",scrollbarWidth:"thin"},railChip:{position:"relative",display:"inline-flex",alignItems:"center",gap:6,flex:"none",maxWidth:190,height:34,padding:"0 4px 0 10px",border:"0.5px solid transparent",borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:13,lineHeight:1,cursor:"pointer",outline:"none",userSelect:"none"},railChipActive:{background:f.bgLayer3,borderColor:f.brand,color:f.labelPrimary,boxShadow:`inset 3px 0 0 ${f.brand}`},railChipHover:{background:f.hover,color:f.labelPrimary},railTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},railTitleDim:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,opacity:.7},transportBadge:{flex:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"1px 4px",borderRadius:3,border:"0.5px solid transparent",fontSize:9,lineHeight:"12px",letterSpacing:"0.04em",textTransform:"uppercase",fontWeight:600},transportBadgeSsh:{color:f.brand,borderColor:f.brand,background:f.bgLayer2},transportBadgeTelnet:{color:f.warn,borderColor:f.warn,background:f.bgLayer2},railTag:{flex:"none",fontSize:11,letterSpacing:"0.02em",color:f.labelTertiary,textTransform:"uppercase"},railDotButton:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:22,height:22,padding:0,border:0,borderRadius:4,background:"transparent",color:f.labelTertiary,font:"inherit",fontSize:13,lineHeight:1,cursor:"pointer",outline:"none"},railSpacer:{flex:"1 1 auto",minWidth:6},railAdd:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:32,height:32,padding:0,marginLeft:"auto",border:`0.5px dashed ${f.borderL2}`,borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:14,lineHeight:1,cursor:"pointer",outline:"none"},controlBar:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,flex:"none",padding:"6px 8px",borderBottom:`0.5px solid ${f.borderL2}`,minHeight:44},controlSpacer:{flex:1,minWidth:0},railConfirmWrap:{flex:"none",padding:"0 8px 6px"},lockChip:{display:"inline-flex",alignItems:"center",gap:5,flex:"none",height:30,padding:"0 10px",borderRadius:999,border:`0.5px solid ${f.borderL2}`,background:f.bgLayer1,fontSize:12,lineHeight:1,whiteSpace:"nowrap"},lockDot:{flex:"none",width:6,height:6,borderRadius:"50%"},pane:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,position:"relative"},termWrap:{display:"flex",flex:1,minHeight:0,minWidth:0,position:"relative",padding:"4px 4px 2px 6px"},statusBar:{display:"flex",alignItems:"center",gap:8,flex:"none",padding:"4px 10px",borderTop:`0.5px solid ${f.borderL2}`,color:f.labelTertiary,fontSize:12,lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden"},quickBar:{display:"flex",flexDirection:"column",gap:4,flex:"none",padding:"5px 8px",borderTop:`0.5px solid ${f.borderL2}`,background:f.bgLayer1},quickBarHead:{display:"flex",alignItems:"center",gap:6,flex:"none",minHeight:26},quickBarTitle:{flex:"none",fontSize:11,letterSpacing:"0.02em",color:f.labelTertiary,textTransform:"uppercase"},quickBarRow:{display:"flex",alignItems:"center",gap:8,flex:"none",overflowX:"auto",overflowY:"hidden",paddingBottom:2,scrollbarWidth:"thin"},quickGroup:{display:"inline-flex",alignItems:"center",gap:4,flex:"none"},quickFolder:{flex:"none",padding:"0 2px",fontSize:10,color:f.labelTertiary,textTransform:"uppercase",letterSpacing:"0.02em"},quickChip:{display:"inline-flex",alignItems:"center",flex:"none",maxWidth:160,height:26,padding:"0 9px",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.labelPrimary,font:"inherit",fontSize:12,lineHeight:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",outline:"none"},quickChipBusy:{color:f.labelTertiary,cursor:"default"},quickBarCollapsed:{display:"flex",alignItems:"center",flex:"none",padding:"3px 8px",borderTop:`0.5px solid ${f.borderL2}`},quickSheetGroup:{display:"flex",flexDirection:"column",gap:2,flex:"none"},statusItem:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},banner:{display:"flex",alignItems:"center",gap:8,flex:"none",padding:"7px 10px",borderBottom:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.warn}`,background:f.bgLayer2,color:f.labelPrimary,fontSize:12,lineHeight:1.45},bannerText:{flex:1,minWidth:0},bannerHint:{color:f.labelTertiary,display:"block"},inlineConfirm:{display:"flex",alignItems:"center",gap:8,flex:"none",flexWrap:"wrap",padding:"6px 8px",border:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.danger}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.labelPrimary,fontSize:12,lineHeight:1.4},inlineConfirmText:{flex:"1 1 120px",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},overlay:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:f.bgOverlay,color:f.labelSecondary,textAlign:"center"},overlayCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,maxWidth:340,padding:"14px 16px",borderRadius:f.radiusMd,border:`0.5px solid ${f.borderL2}`,background:f.bgBase,boxShadow:f.elevationSoft,color:f.labelSecondary},overlayTitle:{margin:0,color:f.labelPrimary,fontSize:13,fontWeight:500,lineHeight:1.4,overflowWrap:"anywhere"},overlayDetail:{margin:0,color:f.labelTertiary,fontSize:11,lineHeight:1.5,overflowWrap:"anywhere"},toast:{position:"absolute",top:8,right:8,zIndex:20,maxWidth:"90%",padding:"8px 12px",borderRadius:f.radiusSm,background:f.toastBg,color:f.toastLabel,fontSize:12,lineHeight:1.45,boxShadow:f.elevationSoft,pointerEvents:"none"},stateWrap:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:10,padding:"24px 18px",textAlign:"center",color:f.labelSecondary,overflow:"auto"},stateTitle:{margin:0,color:f.labelPrimary,fontSize:14,fontWeight:500,lineHeight:1.5,maxWidth:"30ch",overflowWrap:"anywhere"},stateDetail:{margin:0,color:f.labelTertiary,fontSize:12,lineHeight:1.55,maxWidth:"40ch",overflowWrap:"anywhere"},form:{display:"flex",flexDirection:"column",flex:1,minHeight:0},formScroll:{display:"flex",flexDirection:"column",gap:10,flex:1,minHeight:0,padding:"12px 12px 6px",overflowY:"auto",scrollbarWidth:"thin"},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{color:f.labelSecondary,fontSize:12,lineHeight:1.3},row:{display:"flex",alignItems:"flex-end",gap:8,minWidth:0},grow:{flex:1,minWidth:0},portField:{flex:"none",width:88},input:{boxSizing:"border-box",width:"100%",height:32,padding:"0 10px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontSize:13,lineHeight:1.3,outline:"none"},textarea:{boxSizing:"border-box",width:"100%",minHeight:96,padding:"8px 10px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontFamily:"monospace",fontSize:12,lineHeight:1.45,resize:"vertical",outline:"none"},select:{boxSizing:"border-box",width:"100%",height:32,padding:"0 8px",border:`0.5px solid ${f.borderL3}`,borderRadius:f.radiusSm,background:f.bgLayer1,color:f.labelPrimary,font:"inherit",fontSize:13,outline:"none"},hint:{color:f.labelTertiary,fontSize:11,lineHeight:1.45},formError:{padding:"7px 9px",border:`0.5px solid ${f.borderL2}`,borderLeft:`2px solid ${f.danger}`,borderRadius:f.radiusSm,background:f.bgLayer2,color:f.danger,fontSize:12,lineHeight:1.45,overflowWrap:"anywhere"},formActions:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flex:"none",padding:"10px 12px",borderTop:`0.5px solid ${f.borderL2}`},checkboxRow:{display:"flex",alignItems:"center",gap:8,color:f.labelSecondary,fontSize:12,cursor:"pointer",userSelect:"none"},checkbox:{flex:"none",width:16,height:16,margin:0,accentColor:f.brand,cursor:"pointer"},popover:{position:"absolute",top:"calc(100% + 4px)",right:0,zIndex:30,width:"min(320px, 92vw)",maxHeight:300,display:"flex",flexDirection:"column",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusMd,background:f.bgBase,boxShadow:f.elevationPanel,overflow:"hidden"},popoverHeader:{display:"flex",alignItems:"center",gap:6,flex:"none",padding:"8px 10px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontSize:12,fontWeight:600},auditList:{display:"flex",flexDirection:"column",flex:1,minHeight:0,overflowY:"auto",scrollbarWidth:"thin",padding:"2px 0"},auditRow:{display:"flex",alignItems:"baseline",gap:6,padding:"4px 10px",fontSize:12,lineHeight:1.4,color:f.labelSecondary},auditTime:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},auditBadge:{flex:"none",padding:"0 5px",borderRadius:3,border:`0.5px solid ${f.borderL2}`,color:f.labelSecondary,fontSize:11,lineHeight:"15px"},auditDetail:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelSecondary,fontFamily:"monospace",fontSize:11},auditEmpty:{padding:"12px 8px",textAlign:"center",color:f.labelTertiary,fontSize:11},overlayWindow:{position:"absolute",inset:12,zIndex:30,display:"flex",flexDirection:"column",minWidth:0,minHeight:0,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusMd,background:f.bgLayer1,boxShadow:f.elevationPanel,overflow:"hidden"},overlayWindowHead:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:44,padding:"6px 8px 6px 12px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontSize:13,fontWeight:600},overlayWindowTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},overlayWindowBody:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},sheet:{position:"absolute",inset:0,zIndex:15,display:"flex",flexDirection:"column",minWidth:0,minHeight:0,background:f.bgBase,color:f.labelPrimary,overflow:"hidden"},viewHeader:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:46,padding:"6px 8px",borderBottom:`0.5px solid ${f.borderL2}`,color:f.labelPrimary,fontWeight:600},viewHeaderText:{display:"flex",flexDirection:"column",gap:1,flex:1,minWidth:0},viewHeaderTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelPrimary,fontSize:13,lineHeight:1.3},viewHeaderHint:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,fontSize:11,fontWeight:400,lineHeight:1.35},viewHeaderActions:{display:"flex",alignItems:"center",gap:6,flex:"none"},sheetBody:{display:"flex",flexDirection:"column",gap:9,flex:1,minHeight:0,minWidth:0,padding:"10px 10px 8px",overflow:"hidden"},sheetFooter:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:40,padding:"6px 10px",borderTop:`0.5px solid ${f.borderL2}`,color:f.labelTertiary,fontSize:12,lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden"},sectionTitle:{color:f.labelSecondary,fontSize:12,lineHeight:1.35},filterRow:{display:"flex",alignItems:"flex-end",gap:6,minWidth:0,flex:"none"},listBox:{display:"flex",flexDirection:"column",flex:"none",maxHeight:120,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},listToolbar:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,flex:"none",padding:"0 0 8px",borderBottom:`0.5px solid ${f.borderL2}`,marginBottom:8},listToolbarMeta:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,color:f.labelTertiary},folderBar:{display:"flex",alignItems:"center",gap:8,flex:"none",flexWrap:"wrap"},scriptSplit:{display:"flex",alignItems:"stretch",gap:10,flex:1,minHeight:0,minWidth:0},scriptListCol:{display:"flex",flexDirection:"column",gap:6,flex:"none",width:172,minWidth:130,maxWidth:200,minHeight:0},scriptListScroll:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},scriptRowActive:{background:f.bgLayer3,color:f.labelPrimary,boxShadow:`inset 2px 0 0 ${f.brand}`},newChoicePop:{position:"absolute",bottom:"100%",left:0,zIndex:25,display:"flex",flexDirection:"column",gap:4,minWidth:132,padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgOverlay,boxShadow:f.elevationPanel},newChoiceOption:{justifyContent:"flex-start",width:"100%"},scriptListButtons:{display:"flex",alignItems:"center",gap:4,flex:"none",flexWrap:"wrap"},rowBtnSmall:{height:28,padding:"0 7px",fontSize:11},scriptEditCol:{display:"flex",flexDirection:"column",gap:9,flex:1,minWidth:0,minHeight:0},editorGrow:{display:"flex",flexDirection:"column",flex:"1 1 auto",minHeight:0},editorBody:{flex:"1 1 auto",minHeight:120,resize:"none"},runSection:{display:"flex",flexDirection:"column",gap:7,flex:"none",paddingTop:8,borderTop:`0.5px solid ${f.borderL2}`},resultSummary:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,color:f.labelSecondary},pickList:{display:"flex",flexDirection:"column",gap:4,flex:"none",maxHeight:148,padding:"6px 8px",border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1,overflowY:"auto",scrollbarWidth:"thin"},exportBox:{display:"flex",flexDirection:"column",gap:2,flex:"none",padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1},exportRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minWidth:0},exportPath:{flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:11,color:f.labelPrimary},exportMeta:{flex:"none",fontSize:11,color:f.labelTertiary},checkRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:26,cursor:"pointer"},checkLabel:{minWidth:0,fontSize:12,color:f.labelPrimary},pickRow:{display:"flex",alignItems:"center",gap:8,flex:"none",minHeight:26,cursor:"pointer"},pickBox:{flex:"none",width:15,height:15,margin:0,accentColor:f.brand,cursor:"pointer"},pickTitle:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,color:f.labelPrimary},pickMeta:{flex:"0 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,color:f.labelTertiary},listRow:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:1,flex:"none",width:"100%",padding:"6px 9px",border:0,borderBottom:`0.5px solid ${f.borderL1}`,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1.35,textAlign:"left",cursor:"pointer",outline:"none"},listRowActive:{background:f.bgLayer3,color:f.labelPrimary},listRowTitle:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},listRowMeta:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.labelTertiary,fontSize:11,fontVariantNumeric:"tabular-nums"},scrollArea:{display:"flex",flexDirection:"column",flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},matchRow:{display:"flex",alignItems:"baseline",gap:7,flex:"none",padding:"2px 3px",fontFamily:"monospace",fontSize:11,lineHeight:1.5,color:f.labelPrimary},matchTime:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},matchText:{flex:1,minWidth:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},contextText:{flex:1,minWidth:0,color:f.labelTertiary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},matchHit:{color:f.brand,fontWeight:600},dialectTag:{flex:"none",padding:"0 5px",borderRadius:3,fontSize:10,lineHeight:"14px",color:f.labelTertiary,background:f.bgLayer3},resultBox:{display:"flex",flexDirection:"column",gap:1,flex:1,minHeight:0,padding:"4px 0",overflowY:"auto",scrollbarWidth:"thin"},batchLine:{display:"flex",alignItems:"baseline",gap:5,flex:"none",padding:"2px 7px",fontFamily:"monospace",fontSize:11,lineHeight:1.5,whiteSpace:"nowrap"},batchIndex:{flex:"none",color:f.labelTertiary,fontVariantNumeric:"tabular-nums"},batchSession:{flex:"none",color:f.labelTertiary},batchText:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",color:f.labelSecondary},batchPath:{flex:"none",color:f.labelTertiary,whiteSpace:"pre",fontVariantNumeric:"tabular-nums"},batchKind:{flex:"none",color:f.labelTertiary},batchSep:{flex:"none",color:f.labelTertiary},actionRow:{display:"flex",alignItems:"center",gap:6,flex:"none",flexWrap:"wrap"},profileList:{display:"flex",flexDirection:"column",gap:6,flex:1,minHeight:0,minWidth:0,overflowY:"auto",scrollbarWidth:"thin"},profileSection:{display:"flex",flexDirection:"column",gap:2,flex:"none",minWidth:0},profileSectionHeader:{display:"flex",alignItems:"baseline",gap:6,flex:"none",padding:"4px 2px 2px",color:f.labelSecondary,fontSize:12,fontWeight:600},profileCount:{color:f.labelTertiary,fontSize:11,fontWeight:400,fontVariantNumeric:"tabular-nums"},profileRow:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:7,flex:"none",minWidth:0,padding:"8px 9px",border:`0.5px solid ${f.borderL1}`,borderRadius:f.radiusSm,background:f.bgLayer1},profileRowHighlight:{borderColor:f.brand,background:f.bgLayer3},profileMain:{display:"flex",flexDirection:"column",gap:2,flex:"none",minWidth:0},profileName:{color:f.labelPrimary,fontSize:13,fontWeight:600,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},profileAddress:{color:f.labelTertiary,fontFamily:"monospace",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},profileBadges:{display:"flex",alignItems:"center",gap:4,flexWrap:"wrap"},badge:{flex:"none",padding:"1px 5px",borderRadius:3,border:`0.5px solid ${f.borderL2}`,color:f.labelSecondary,fontSize:11,lineHeight:"16px"},profileActions:{display:"flex",alignItems:"center",gap:5,flex:"none",flexWrap:"wrap",minWidth:0},rowBtn:{height:30,padding:"0 8px",fontSize:12},inlineRow:{display:"flex",alignItems:"center",gap:6,flex:"none",flexWrap:"wrap",minWidth:0},folderPickerRow:{display:"flex",alignItems:"flex-end",gap:8,flex:"none",minWidth:0},listGroupHeader:{display:"flex",alignItems:"baseline",gap:6,flex:"none",padding:"4px 2px 2px",color:f.labelSecondary,fontSize:11,fontWeight:600},templateRow:{display:"flex",alignItems:"center",gap:6,flex:"none",minWidth:0}};function Zi(e){return e?`inset 0 0 0 1px ${f.focusRing}`:void 0}var Wp={background:"#17191d",foreground:"#e6e6e6",cursor:"#e6e6e6",cursorAccent:"#17191d",selectionBackground:"rgba(77, 107, 254, 0.35)",black:"#1f2125",red:"#e5484d",green:"#2fbf71",yellow:"#d9a300",blue:"#4d8bff",magenta:"#c678dd",cyan:"#56b6c2",white:"#d7dae0",brightBlack:"#5c6370",brightRed:"#ff6b70",brightGreen:"#5ad68f",brightYellow:"#f0c040",brightBlue:"#7aa7ff",brightMagenta:"#e39ff6",brightCyan:"#7fd4de",brightWhite:"#ffffff"},zp=/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]*\)|hsla?\([^)]*\))$/i;function Fo(e){if(!(typeof document>"u"||typeof window>"u"))try{let t=window.getComputedStyle(document.documentElement).getPropertyValue(e);if(typeof t!="string")return;let i=t.trim();return!i||i.includes("var(")?void 0:zp.test(i)?i:void 0}catch{return}}function Ho(){let e={...Wp},t=Fo("--dsw-alias-bg-layer-1")||Fo("--dsw-alias-bg-base"),i=Fo("--dsw-alias-label-primary");return t&&(e.background=t,e.cursorAccent=t),i&&(e.foreground=i,e.cursor=i),e}var $p='Consolas, "Cascadia Mono", "SFMono-Regular", Menlo, "Courier New", monospace';function qc(e){return{allowProposedApi:!0,convertEol:!1,cursorBlink:!0,fontFamily:$p,fontSize:12,lineHeight:1.18,scrollback:4e3,scrollSensitivity:1.4,theme:Ho(),...e}}var Vc=`
|
|
355
355
|
.dsst-term-host {
|
|
356
356
|
position: relative;
|
|
357
357
|
display: flex;
|
|
@@ -382,18 +382,18 @@ ${u.join(`
|
|
|
382
382
|
.dsst-term-host .xterm.xterm-focus .xterm-cursor-layer {
|
|
383
383
|
opacity: 1;
|
|
384
384
|
}
|
|
385
|
-
`;var Ii=require("react/jsx-runtime"),Wp=32768,Ah=8192;function Mh({t:e,session:t,onLinkChange:i,reset:s}){let r=(0,mt.useRef)(null),n=(0,mt.useRef)(null),o=(0,mt.useRef)(typeof e=="function"?e:g=>g),l=(0,mt.useRef)(t),h=(0,mt.useRef)(i),[a,u]=(0,mt.useState)(null),d=(0,mt.useRef)(vr(s&&s.seq?s.seq:0));o.current=typeof e=="function"?e:g=>g,l.current=t,h.current=i;let m=!!t.permission.humanWriteBlocked,p=t.state==="closed"||t.state==="failed",_=t.state==="disconnected";return(0,mt.useEffect)(()=>{let g=r.current;if(!g)return;let y=!1,x=null,j=0,z=0,C=null,O=null,X=null,$=null,ye=null,de={text:"",busy:!1},fe=()=>l.current,Z=()=>o.current,we=T=>{if(!y)try{h.current?.(T)}catch(b){console.error("[aiterm] link reporter failed",b)}},k=()=>{if(de.busy||de.text===""||y)return;let T=fe();if(T.state!=="open"||T.permission.humanWriteBlocked){de.text="";return}let b=de.text.slice(0,Ah);de.text=de.text.slice(Ah),de.busy=!0,pe("sessions.input",{id:fe().id,data:b}).catch(M=>{if(y)return;let B=M&&typeof M.code=="string"?M.code:"";if(B==="HUMAN_WRITE_BLOCKED"){de.text="",G(I(Z(),"blockedTitle"));return}(B==="NOT_CONNECTED"||B==="SESSION_NOT_FOUND"||B==="WRITE_FAILED"||B==="INPUT_TOO_LARGE")&&(de.text=""),G(I(Z(),"inputFailed",{message:oe(M)}))}).finally(()=>{de.busy=!1,y||k()})},E=()=>{if(!(y||!ye||!$))try{if(g.clientWidth<24||g.clientHeight<24)return;ye.fit(),Gr(fe().id,$.cols,$.rows)}catch{}},A=()=>{y||(z&&cancelAnimationFrame(z),z=requestAnimationFrame(()=>{z=0,E()}))};try{$=new Rh(Bh({cols:Math.max(20,Number(fe().cols)||80),rows:Math.max(5,Number(fe().rows)||24),disableStdin:!!fe().permission.humanWriteBlocked||fe().state!=="open"})),ye=new Th,$.loadAddon(ye),$.open(g),n.current=$}catch(T){console.error("[aiterm] terminal failed to open",T),u(oe(T)),we("error");return}return O=$.onData(T=>{if(y||!T)return;let b=fe();if(b.state==="open"&&!b.permission.humanWriteBlocked){if(de.text.length+T.length>Wp){de.text="",G(I(Z(),"inputOverflow"));return}de.text+=T,queueMicrotask(k)}}),X=$.onResize(({cols:T,rows:b})=>{y||(Gr(fe().id,T,b),j&&clearTimeout(j),j=window.setTimeout(()=>{j=0,!y&&pe("sessions.resize",{id:fe().id,cols:T,rows:b}).catch(()=>{})},250))}),typeof ResizeObserver<"u"&&(C=new ResizeObserver(A),C.observe(g)),A(),(()=>{let T;try{let b=Pr(),M=b===void 0?"":"&owner="+encodeURIComponent(b);T=new EventSource($i+"/events?sessionId="+encodeURIComponent(fe().id)+M)}catch(b){console.error("[aiterm] event stream failed",b),we("error");return}x=T,we("connecting"),T.onopen=()=>{y||we("open")},T.onerror=()=>{if(y)return;let b=fe();if(b.state==="closed"||b.state==="failed"){try{T.close()}catch{}we("closed");return}we("error")},T.onmessage=b=>{if(y)return;let M=Bs(b.data);if(M)try{if(M.type==="hello"){if(!$)return;$.reset();let B=Ds(M.replay);if(B.length>0?$.write(B):pe("sessions.replay",{id:fe().id}).then(te=>{if(y||!$)return;let Se=Ds(te&&te.replay);Se.length>0&&$.write(Se)}).catch(()=>{}),M.session){Lt(M.session);let te=ma(fe().id);te&&te.seq&&d.current.markApplied(te.seq)}we("open"),A()}else if(M.type==="data"){if(!$||typeof M.chunk!="string"||M.chunk==="")return;let B=Ds(M.chunk);B.length>0&&$.write(B)}else if(M.type==="reset")Yr(M);else if(M.type==="state")Lt(M.session);else if(M.type==="exit"){let B=typeof M.code=="number"?M.code:null;Ri(fe().id,typeof M.reason=="string"?M.reason:void 0),we("closed"),G(B===null?Z()("sessionEnded"):I(Z(),"sessionExited",{code:B}));try{T.close()}catch{}x===T&&(x=null)}else M.type==="audit"&&xa(fe().id,M.entry)}catch(B){console.error("[aiterm] terminal frame failed",B)}}})(),()=>{y=!0,j&&clearTimeout(j),z&&cancelAnimationFrame(z);try{C?.disconnect()}catch{}try{x?.close()}catch{}try{O?.dispose()}catch{}try{X?.dispose()}catch{}try{$?.dispose()}catch{}n.current=null}},[t.id]),(0,mt.useEffect)(()=>{let g=n.current;if(g)try{g.options.disableStdin=m||p||t.state!=="open",(m||t.state!=="open")&&g.blur()}catch(y){console.error("[aiterm] could not update stdin gate",y)}},[m,p,t.state]),(0,mt.useEffect)(()=>{let g=n.current,y=s&&s.seq?s.seq:0;if(!(!g||!y))try{if(!yr(g,o.current,y,d.current))return;try{g.scrollToBottom()}catch{}}catch(x){console.error("[aiterm] could not clear the screen after a reconnect",x)}},[s?s.seq:0,t.id]),(0,mt.useEffect)(()=>{if(typeof MutationObserver>"u"||typeof document>"u")return;let g=()=>{let j=n.current;if(j)try{j.options.theme=yo()}catch{}},y=new MutationObserver(g),x={attributes:!0,attributeFilter:["class","style","data-theme","data-color-scheme"]};try{y.observe(document.documentElement,x),document.body&&y.observe(document.body,x)}catch{}return()=>{try{y.disconnect()}catch{}}},[]),(0,Ii.jsxs)("div",{style:{display:"flex",flex:1,minWidth:0,minHeight:0,position:"relative"},children:[(0,Ii.jsx)("style",{children:Dh+Lh}),(0,Ii.jsx)("div",{ref:r,className:"dsst-term-host",title:_?I(o.current,"disconnectedHint"):void 0}),a?(0,Ii.jsx)("div",{role:"alert",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:12,textAlign:"center",color:f.danger,fontSize:11,lineHeight:1.5,background:f.bgBase},children:I(o.current,"connectFailed",{message:a})}):null]})}var It=require("react");var yi=require("react");var F=require("react/jsx-runtime");function vs(){let[e,t]=(0,yi.useState)(!1);return{focus:e,focusProps:{onFocus(s){let r=!1;try{let n=s&&s.currentTarget;r=typeof n.matches=="function"?n.matches(":focus-visible"):!1}catch{r=!1}t(r)},onBlur(){t(!1)}}}}var zp={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,flex:"none",height:32,padding:"0 12px",border:"0.5px solid transparent",borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function $p(e,t,i){return e==="primary"?{background:t?f.primaryHover:f.primaryFill,color:f.labelForeground,borderColor:f.primaryFill}:e==="danger"?{background:t?f.hoverDanger:"transparent",color:f.danger,borderColor:t?f.borderL2:"transparent"}:e==="outline"?{background:t?f.hover:"transparent",borderColor:f.borderL2,color:f.labelPrimary}:{background:t||i?f.hover:"transparent",color:t||i?f.labelPrimary:f.labelSecondary,borderColor:"transparent"}}function J({children:e,onClick:t,variant:i="default",disabled:s=!1,busy:r=!1,title:n,ariaLabel:o,style:l}){let[h,a]=(0,yi.useState)(!1),{focus:u,focusProps:d}=vs(),m=s||r;return(0,F.jsx)("button",{type:"button",title:n,"aria-label":o,"aria-busy":r||void 0,disabled:m,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),...d,onClick:p=>{if(!(m||typeof t!="function"))try{let _=t(p);_&&typeof _.catch=="function"&&_.catch(()=>{})}catch(_){console.error("[aiterm] button action failed",_)}},style:{...zp,...$p(i,h&&!m),...m?{opacity:.45,cursor:"default"}:null,boxShadow:Pi(u),...l},children:r?"…":e})}function Pt({children:e,onClick:t,title:i,ariaLabel:s,active:r=!1,danger:n=!1,disabled:o=!1,size:l=30}){let[h,a]=(0,yi.useState)(!1),{focus:u,focusProps:d}=vs();return(0,F.jsx)("button",{type:"button",title:i,"aria-label":s||i,"aria-pressed":r,disabled:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),...d,onClick:m=>{if(!(o||typeof t!="function"))try{let p=t(m);p&&typeof p.catch=="function"&&p.catch(()=>{})}catch(p){console.error("[aiterm] icon action failed",p)}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:l,height:l,padding:0,border:"0.5px solid transparent",borderRadius:f.radiusSm,background:h&&!o?n?f.hoverDanger:f.hover:"transparent",color:n?f.danger:h&&!o?f.labelPrimary:f.labelSecondary,font:"inherit",fontSize:13,lineHeight:1,cursor:o?"default":"pointer",outline:"none",opacity:o?.45:1,boxShadow:Pi(u)},children:e})}function Sr({options:e,value:t,onChange:i,disabled:s=!1,label:r}){return(0,F.jsx)("div",{role:"group","aria-label":r,style:{display:"inline-flex",alignItems:"stretch",flex:"none",height:30,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,overflow:"hidden"},children:e.map((n,o)=>(0,F.jsx)(Kp,{option:n,active:n.value===t,disabled:s,last:o===e.length-1,onSelect:()=>{!s&&n.value!==t&&i(n.value)}},n.value))})}function Kp({option:e,active:t,disabled:i,last:s,onSelect:r}){let[n,o]=(0,yi.useState)(!1),{focus:l,focusProps:h}=vs();return(0,F.jsx)("button",{type:"button",role:"button","aria-pressed":t,title:e.hint,disabled:i,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),...h,onClick:r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:42,height:"100%",padding:"0 10px",border:0,borderRight:s?0:`0.5px solid ${f.borderL2}`,background:t?f.bgLayer3:n&&!i?f.hover:"transparent",color:i?f.labelTertiary:t?f.labelPrimary:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1,fontWeight:t?600:400,cursor:i?"default":"pointer",outline:"none",boxShadow:Pi(l),opacity:i?.5:1},children:e.label})}function Ph({state:e}){if(e==="disconnected")return(0,F.jsx)("span",{"aria-hidden":"true",style:{flex:"none",width:6,height:6,boxSizing:"border-box",borderRadius:"50%",border:`1px solid ${f.warn}`,background:"transparent"}});let t=e==="open"?f.success:e==="failed"?f.danger:e==="connecting"?f.warn:f.labelTertiary;return(0,F.jsx)("span",{"aria-hidden":"true",style:{flex:"none",width:6,height:6,borderRadius:"50%",background:t,opacity:e==="closed"?.6:1}})}function Pe({label:e,hint:t,children:i,style:s}){return(0,F.jsxs)("label",{style:{...c.field,...s},children:[(0,F.jsx)("span",{style:c.label,children:e}),i,t?(0,F.jsx)("span",{style:c.hint,children:t}):null]})}function So({toast:e}){return!e||!e.text?null:(0,F.jsx)("div",{role:"status","aria-live":"polite",style:c.toast,children:e.text})}function bo({title:e,hint:t,onBack:i,backLabel:s,onClose:r,closeLabel:n,actions:o}){return(0,F.jsxs)("div",{style:c.viewHeader,children:[i?(0,F.jsx)(Pt,{title:s||e,onClick:i,children:(0,F.jsx)(Up,{})}):null,(0,F.jsxs)("div",{style:c.viewHeaderText,children:[(0,F.jsx)("span",{style:c.viewHeaderTitle,title:e,children:e}),t?(0,F.jsx)("span",{style:c.viewHeaderHint,children:t}):null]}),o?(0,F.jsx)("div",{style:c.viewHeaderActions,children:o}):null,r?(0,F.jsx)(Pt,{title:n||e,onClick:r,children:(0,F.jsx)(ys,{})}):null]})}function ri({message:e,confirmLabel:t,cancelLabel:i,onConfirm:s,onCancel:r,busy:n=!1,danger:o=!0}){return(0,F.jsxs)("div",{style:c.inlineConfirm,role:"alertdialog","aria-label":e,onKeyDown:l=>{l&&l.key==="Escape"&&(l.stopPropagation(),!n&&typeof r=="function"&&r())},children:[(0,F.jsx)("span",{style:c.inlineConfirmText,title:e,children:e}),(0,F.jsx)(J,{variant:o?"danger":"primary",busy:n,disabled:n,onClick:s,children:t}),(0,F.jsx)(J,{disabled:n,onClick:r,children:i})]})}function Si({title:e,onBack:t,backLabel:i,onClose:s,closeLabel:r,actions:n,children:o,footer:l}){return(0,F.jsxs)("div",{style:c.sheet,role:"dialog","aria-modal":"true","aria-label":e,children:[(0,F.jsx)(bo,{title:e,onBack:t,backLabel:i,onClose:s,closeLabel:r,actions:n}),(0,F.jsx)("div",{style:c.sheetBody,children:o}),l!=null?(0,F.jsx)("div",{style:c.sheetFooter,children:l}):null]})}function Ih({title:e,onClose:t,closeLabel:i,children:s}){return(0,yi.useEffect)(()=>{if(typeof document>"u"||typeof document.addEventListener!="function")return;let r=n=>{!n||n.key!=="Escape"||(n.stopPropagation(),typeof n.preventDefault=="function"&&n.preventDefault(),typeof t=="function"&&t())};return document.addEventListener("keydown",r,!0),()=>{try{document.removeEventListener("keydown",r,!0)}catch{}}},[t]),(0,F.jsxs)("div",{style:c.overlayWindow,role:"dialog","aria-modal":"false","aria-label":e,children:[(0,F.jsxs)("div",{style:c.overlayWindowHead,children:[(0,F.jsx)("span",{style:c.overlayWindowTitle,title:e,children:e}),(0,F.jsx)("span",{style:c.controlSpacer}),(0,F.jsx)(Pt,{title:i||e,onClick:t,children:(0,F.jsx)(ys,{})})]}),(0,F.jsx)("div",{style:c.overlayWindowBody,children:s})]})}var Tt=(e,t,i)=>(0,F.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",style:{flex:"none",...i},children:t});function Up({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M9.8 3.6 5.4 8l4.4 4.4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),(0,F.jsx)("path",{d:"M5.6 8h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]}))}function Oh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M2.5 4.5 6 8l-3.5 3.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,F.jsx)("path",{d:"M8.5 11.5h5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}function Nh({size:e=15}){return Tt(e,(0,F.jsx)(F.Fragment,{children:(0,F.jsx)("path",{d:"M8 3.5v9M3.5 8h9",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})}))}function ys({size:e=14}){return Tt(e,(0,F.jsx)("path",{d:"m4 4 8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}))}function Fh({size:e=15}){return Tt(e,(0,F.jsx)(F.Fragment,{children:(0,F.jsx)("path",{d:"M3 4h10M3 8h10M3 12h6",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})}))}function wo({size:e=13}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("rect",{x:"3.5",y:"7",width:"9",height:"6",rx:"1.2",stroke:"currentColor",strokeWidth:"1.1"}),(0,F.jsx)("path",{d:"M5.5 7V5.4a2.5 2.5 0 0 1 5 0V7",stroke:"currentColor",strokeWidth:"1.1"})]}))}function Hh({size:e=12,open:t=!1}){return(0,F.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",style:{flex:"none",transform:t?"rotate(180deg)":"none"},children:(0,F.jsx)("path",{d:"m4 6 4 4 4-4",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Wh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("circle",{cx:"8",cy:"8",r:"5.4",stroke:"currentColor",strokeWidth:"1.1"}),(0,F.jsx)("path",{d:"M8 4.8V8l2.2 1.6",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})]}))}function zh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M4 2.6h5.2L12 5.4v8H4z",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"}),(0,F.jsx)("path",{d:"M6 7.4h4M6 9.8h4",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round"})]}))}function $h({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M2.4 4.4a1 1 0 0 1 1-1h3l1.2 1.4h4.9a1 1 0 0 1 1 1v6.8a1 1 0 0 1-1 1H3.4a1 1 0 0 1-1-1z",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"}),(0,F.jsx)("path",{d:"M5.6 9.2h4.8",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round"})]}))}function Kh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("rect",{x:"5.4",y:"5.4",width:"7",height:"7",rx:"1.1",stroke:"currentColor",strokeWidth:"1.1"}),(0,F.jsx)("path",{d:"M10.4 5.4V4.2A1.2 1.2 0 0 0 9.2 3H4.2A1.2 1.2 0 0 0 3 4.2v5a1.2 1.2 0 0 0 1.2 1.2h1.2",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"})]}))}function Uh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M8 2.8v5.4",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),(0,F.jsx)("path",{d:"M4.6 5.2a4.4 4.4 0 1 0 6.8 0",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}function qh({size:e=15}){return Tt(e,(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("path",{d:"M13 5.6V2.8m0 2.8H10.2",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,F.jsx)("path",{d:"M12.6 8a4.6 4.6 0 1 1-1.4-3.3",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}var Vh="dsh.aiterm.scriptOrder";function Ss(){try{let e=globalThis.localStorage&&globalThis.localStorage.getItem(Vh);if(!e)return{};let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function br(e){try{if(!globalThis.localStorage)return;globalThis.localStorage.setItem(Vh,JSON.stringify(e))}catch{}}function Oi(e,t){let i=Array.isArray(t)?t.filter(o=>typeof o=="string"&&o!==""):[],s=Ss(),r=Array.isArray(s[e])?s[e].filter(o=>i.includes(o)):[],n=i.filter(o=>!r.includes(o));return r.concat(n)}function jh(e,t,i,s){let r=Oi(e,t),n=r.indexOf(i);if(n<0)return{names:r,moved:!1};let o=n+(s<0?-1:1);if(o<0||o>=r.length)return{names:r,moved:!1};let l=r.slice();l[n]=r[o],l[o]=r[n];let h=Ss();return h[e]=l,br(h),{names:l,moved:!0}}function Yh(e,t){let i=Ss(),s=Array.isArray(i[e])?i[e]:[];s.includes(t)&&(i[e]=s.filter(r=>r!==t),br(i))}function Gh(e,t){let i=Ss();Array.isArray(i[e])&&(i[t]=i[e],delete i[e],br(i))}function Xh(e){let t=Ss();Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],br(t))}var Ie=require("react/jsx-runtime"),qp=200,Jh="dsh.aiterm.quickHiddenFolders";function Vp(){try{let e=globalThis.localStorage&&globalThis.localStorage.getItem(Jh);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(i=>typeof i=="string"):[]}catch{return[]}}function jp(e){try{if(!globalThis.localStorage)return;globalThis.localStorage.setItem(Jh,JSON.stringify(e))}catch{}}function Yp(e){let t=new Map;for(let s of e){let r=s.folder||"";t.has(r)||t.set(r,[]),t.get(r).push(s)}return[...t.keys()].sort((s,r)=>s===""?1:r===""?-1:s.localeCompare(r)).map(s=>{let r=t.get(s),n=Oi(s,r.map(o=>o.name));return{folder:s,items:n.map(o=>r.find(l=>l.name===o)).filter(Boolean)}})}function Zh({t:e,sessionId:t,open:i,onToggle:s,onOpenLibrary:r}){let[n,o]=(0,It.useState)([]),[l,h]=(0,It.useState)("idle"),[a,u]=(0,It.useState)(null),[d,m]=(0,It.useState)(()=>Vp()),[p,_]=(0,It.useState)(!1),g=(0,It.useRef)(!0);(0,It.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]),(0,It.useEffect)(()=>{if(!i)return;let C=!1;return h(O=>O==="idle"?"loading":O),Ms().then(O=>{if(C||!g.current)return;let X=(O&&Array.isArray(O.scripts)?O.scripts:[]).map(xi).filter(Boolean);o(Yp(X.slice(0,qp))),h(X.length===0?"empty":"ready")}).catch(()=>{C||!g.current||h("error")}),()=>{C=!0}},[i]);let y=n.map(C=>C.folder),x=n.filter(C=>!d.includes(C.folder)),j=C=>{let O=d.includes(C)?d.filter(X=>X!==C):[...d,C];m(O),jp(O)},z=async C=>{if(a===null){if(!t){G(e("quickScriptsNoSession"));return}u(C.name);try{let O=await Os({name:C.name,params:{},sessionId:t}),$=(O&&O.result&&Array.isArray(O.result.runs)?O.result.runs:[]).filter(ye=>ye&&ye.ok===!1).length;G($>0?I(e,"quickScriptsPartial",{name:C.name,failed:$}):I(e,"quickScriptsDone",{name:C.name}))}catch(O){G(I(e,"quickScriptsFailed",{name:C.name,message:oe(O)}))}finally{g.current&&u(null)}}};return i?(0,Ie.jsxs)("div",{style:c.quickBar,role:"toolbar","aria-label":e("quickScripts"),children:[(0,Ie.jsxs)("div",{style:c.quickBarHead,children:[(0,Ie.jsx)("span",{style:c.quickBarTitle,children:e("quickScripts")}),(0,Ie.jsx)("span",{style:c.controlSpacer}),l==="loading"?(0,Ie.jsx)("span",{style:c.hint,children:e("loading")}):null,l==="error"?(0,Ie.jsx)("span",{style:c.hint,children:e("quickScriptsLoadFailed")}):null,(0,Ie.jsx)(J,{active:p,onClick:()=>_(C=>!C),title:e("quickFolderVisibility"),children:e("quickFolderVisibility")}),(0,Ie.jsx)(J,{onClick:r,title:e("scriptsTitle"),children:e("quickScriptsManage")}),(0,Ie.jsx)(J,{onClick:s,title:e("quickScriptsHide"),children:e("quickScriptsHide")})]}),p?(0,Ie.jsxs)("div",{style:c.quickBarRow,role:"group","aria-label":e("quickFolderVisibility"),children:[y.length===0?(0,Ie.jsx)("span",{style:c.hint,children:e("quickScriptsEmpty")}):null,y.map(C=>(0,Ie.jsxs)("label",{style:c.pickRow,children:[(0,Ie.jsx)("input",{type:"checkbox",checked:!d.includes(C),onChange:()=>j(C),style:c.pickBox}),(0,Ie.jsx)("span",{style:c.pickTitle,children:C||e("scriptsUngrouped")})]},C||"__ungrouped"))]}):null,(0,Ie.jsx)("div",{style:c.quickBarRow,children:l==="empty"?(0,Ie.jsx)("span",{style:c.hint,children:e("quickScriptsEmpty")}):x.map(C=>(0,Ie.jsxs)("span",{style:c.quickGroup,children:[(0,Ie.jsx)("span",{style:c.quickFolder,children:C.folder||e("scriptsUngrouped")}),C.items.map(O=>(0,Ie.jsx)("button",{type:"button",style:{...c.quickChip,...a===O.name?c.quickChipBusy:null},title:`${O.name}${O.folder?` · ${O.folder}`:""} · ${I(e,"scriptsSteps",{count:O.stepCount})}`,disabled:a!==null,onClick:()=>z(O),children:a===O.name?"…":O.name},O.name))]},C.folder||"__ungrouped"))})]}):(0,Ie.jsx)("div",{style:c.quickBarCollapsed,children:(0,Ie.jsx)(J,{title:e("quickScripts"),ariaLabel:e("quickScripts"),onClick:s,children:e("quickScriptsShow")})})}var We=require("react");var V=require("react/jsx-runtime"),Gp=["password","privateKey","agent","none"],wr="__new__";function Qh(e){return e==="telnet"?"23":"22"}function Xp(e,t){return e===wr?String(t||"").trim():typeof e=="string"?e:""}function ec({t:e,onCancel:t,onSaved:i,draft:s}){let r=!!(s&&typeof s.id=="string"&&s.id),[n,o]=(0,We.useState)([]),[l,h]=(0,We.useState)([]),[a,u]=(0,We.useState)(!0),[d,m]=(0,We.useState)(null),[p,_]=(0,We.useState)(r?s.transport:"ssh"),[g,y]=(0,We.useState)(r?s.id:""),[x,j]=(0,We.useState)(r?s.host:""),[z,C]=(0,We.useState)(String(r?s.port:Qh("ssh"))),[O,X]=(0,We.useState)(r?s.username:""),[$,ye]=(0,We.useState)(r?s.authType:"password"),[de,fe]=(0,We.useState)(""),[Z,we]=(0,We.useState)(""),[k,E]=(0,We.useState)(""),[A,L]=(0,We.useState)(!1),[T,b]=(0,We.useState)(r?s.name:""),[M,B]=(0,We.useState)(r&&s.folder?s.folder:""),[te,Se]=(0,We.useState)(""),[ne,_e]=(0,We.useState)(!1),[Oe,se]=(0,We.useState)(null);(0,We.useEffect)(()=>{let D=!1;return u(!0),Ls().then(Y=>{if(D)return;let Ne=As(Y);o(Ne.profiles),h(Ne.folders.map(Ae=>Ae.name))}).catch(Y=>{D||m(oe(Y))}).finally(()=>{D||u(!1)}),()=>{D=!0}},[]);let W=[...new Set([...l,...r&&s.folder?[s.folder]:[]])],q=r?s:n.find(D=>D.id===g),le=!!q&&($==="password"&&q.hasPassword||$==="privateKey"&&q.hasPrivateKey),Ue=le?e("profileUsesSavedSecret"):!!q&&!le&&($==="password"||$==="privateKey")?e("profileNeedsSecretHint"):null,ot=D=>{_(D),r||y(""),C(Y=>Y==="22"||Y==="23"||Y===""?Qh(D):Y)},re=()=>{g&&!r&&y("")},Ct=D=>{if(y(D),!D)return;let Y=n.find(Ne=>Ne.id===D);Y&&(_(Y.transport),j(Y.host),C(String(Y.port)),X(Y.username),ye(Y.authType),B(Y.folder||""),fe(""),we(""),E(""),!T&&Y.name&&b(`${Y.name} copy`))},oi=D=>{if(L(D),D&&!T.trim()){let Y=x.trim()?`${O.trim()?`${O.trim()}@`:""}${x.trim()}`:"profile";b(Y)}},ft=()=>{if(!x.trim())return e("errorHostRequired");if(p==="ssh"&&O.trim().length===0)return e("errorUsernameRequired");let D=Number(z);return!Number.isInteger(D)||D<1||D>65535?e("errorPort"):null},bi=D=>Yo({id:r?s.id:void 0,order:r?s.order:void 0,name:D,transport:p,host:x,port:Number(z),username:O,authType:$,folder:Xp(M,te),password:de,privateKey:Z,passphrase:k}),P=async D=>{if(D&&typeof D.preventDefault=="function"&&D.preventDefault(),ne)return;let Y=ft();if(Y){se(Y);return}let Ne=T.trim();if(!Ne){se(e("profilesNameRequired"));return}se(null),_e(!0);try{let Ae=await Nr(bi(Ne)),qe=Ae&&Ae.profile&&Ae.profile.id?Ae.profile.id:s.id;G(e("profilesSaved")),typeof i=="function"?i(qe):typeof t=="function"&&t()}catch(Ae){se(I(e,"profilesSaveFailed",{message:oe(Ae)}))}finally{_e(!1)}},me=async D=>{if(D&&typeof D.preventDefault=="function"&&D.preventDefault(),ne)return;if(r){await P();return}let Y=ft();if(Y){se(Y);return}se(null),_e(!0);try{let Ne=x.trim(),Ae=Number(z),qe={transport:p,host:Ne,port:Ae,cols:100,rows:30};if(g&&(qe.profileId=g),p==="ssh"){let pt=O.trim();qe.username=pt,qe.authType=$,$==="password"&&de&&(qe.password=de),$==="privateKey"&&(Z.trim()&&(qe.privateKey=Z),k&&(qe.passphrase=k))}let Ce=await pe("sessions.create",qe),at=Yt(Ce&&Ce.session);if(Ce&&Ce.session&&Lt(Ce.session),at&&hi(at.id),A){let pt=T.trim()||`${O.trim()?`${O.trim()}@`:""}${Ne}`;try{let ai=await Nr(bi(pt));ai&&ai.profile&&ai.profile.id&&ba(ai.profile.id),G(e("profilesSaved"))}catch(ai){G(I(e,"profileSaveFailed",{message:oe(ai)}))}}}catch(Ne){se(I(e,"connectFailed",{message:Ho(e,Ne)}))}finally{_e(!1)}};return(0,V.jsxs)("form",{style:c.form,onSubmit:me,noValidate:!0,children:[(0,V.jsx)(bo,{title:e(r?"profilesEditTitle":"connectTitle"),hint:r?void 0:e("connectHint"),onBack:typeof t=="function"?t:void 0,backLabel:e("back")}),(0,V.jsxs)("div",{style:c.formScroll,children:[r?(0,V.jsx)("span",{style:c.hint,children:e("profilesEditHint")}):null,(0,V.jsxs)("div",{style:c.row,children:[(0,V.jsx)("div",{style:c.grow,children:(0,V.jsx)(Pe,{label:e("transport"),children:(0,V.jsxs)("select",{style:c.select,value:p,onChange:D=>ot(D.target.value),disabled:ne,children:[(0,V.jsx)("option",{value:"ssh",children:"SSH"}),(0,V.jsx)("option",{value:"telnet",children:"Telnet"})]})})}),r?null:(0,V.jsxs)("div",{style:{...c.field,flex:1.4,minWidth:0},children:[(0,V.jsx)("span",{style:c.label,children:e("profile")}),(0,V.jsxs)("select",{style:c.select,value:g,onChange:D=>Ct(D.target.value),disabled:ne||a,children:[(0,V.jsx)("option",{value:"",children:e(a?"profileLoading":"profileManual")}),n.map(D=>(0,V.jsx)("option",{value:D.id,children:`${D.name} · ${D.transport} ${D.host}`},D.id))]})]})]}),!a&&n.length===0&&!r?(0,V.jsx)("span",{style:c.hint,children:e("profileEmpty")}):null,d?(0,V.jsx)("span",{style:c.hint,children:I(e,"profileLoadFailed",{message:d})}):null,(0,V.jsxs)("div",{style:c.row,children:[(0,V.jsx)("div",{style:c.grow,children:(0,V.jsx)(Pe,{label:e("host"),children:(0,V.jsx)("input",{style:c.input,value:x,onChange:D=>{re(),j(D.target.value)},placeholder:"10.0.0.5",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:ne})})}),(0,V.jsx)("div",{style:c.portField,children:(0,V.jsx)(Pe,{label:e("port"),children:(0,V.jsx)("input",{style:c.input,value:z,onChange:D=>{re(),C(D.target.value.replace(/[^0-9]/g,""))},inputMode:"numeric",disabled:ne})})})]}),p==="ssh"?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Pe,{label:e("username"),children:(0,V.jsx)("input",{style:c.input,value:O,onChange:D=>{re(),X(D.target.value)},placeholder:"root",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,disabled:ne})}),(0,V.jsx)(Pe,{label:e("authType"),children:(0,V.jsx)("select",{style:c.select,value:$,onChange:D=>{re(),ye(D.target.value)},disabled:ne,children:Gp.map(D=>(0,V.jsx)("option",{value:D,children:e(`auth${D.charAt(0).toUpperCase()}${D.slice(1)}`)},D))})}),$==="password"?(0,V.jsx)(Pe,{label:e("password"),hint:Ue||e("passwordHint"),children:(0,V.jsx)("input",{style:c.input,type:"password",value:de,onChange:D=>fe(D.target.value),autoComplete:"new-password",disabled:ne})}):null,$==="privateKey"?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Pe,{label:e("privateKey"),hint:Ue||e("privateKeyHint"),children:(0,V.jsx)("textarea",{style:c.textarea,value:Z,onChange:D=>we(D.target.value),spellCheck:!1,autoComplete:"off",disabled:ne})}),(0,V.jsx)(Pe,{label:e("passphrase"),children:(0,V.jsx)("input",{style:c.input,type:"password",value:k,onChange:D=>E(D.target.value),autoComplete:"new-password",disabled:ne})})]}):null]}):(0,V.jsx)("span",{style:c.hint,children:e("passwordHint")}),(0,V.jsx)(Pe,{label:e("folder"),hint:M===wr?e("folderName"):void 0,children:(0,V.jsxs)("select",{style:c.select,value:M,"aria-label":e("folder"),onChange:D=>B(D.target.value),disabled:ne,children:[(0,V.jsx)("option",{value:"",children:e("folderNone")}),W.map(D=>(0,V.jsx)("option",{value:D,children:D},D)),(0,V.jsx)("option",{value:wr,children:e("folderNew")})]})}),M===wr?(0,V.jsx)(Pe,{label:e("folderName"),children:(0,V.jsx)("input",{style:c.input,value:te,"aria-label":e("folderName"),placeholder:e("folderName"),autoComplete:"off",spellCheck:!1,onChange:D=>Se(D.target.value),disabled:ne})}):null,r?(0,V.jsx)(Pe,{label:e("profileName"),children:(0,V.jsx)("input",{style:c.input,value:T,"aria-label":e("profileName"),onChange:D=>b(D.target.value),disabled:ne})}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)("label",{style:c.checkboxRow,children:[(0,V.jsx)("input",{type:"checkbox",style:c.checkbox,checked:A,onChange:D=>oi(D.target.checked),disabled:ne}),e("saveProfile")]}),A?(0,V.jsx)(Pe,{label:e("profileName"),children:(0,V.jsx)("input",{style:c.input,value:T,"aria-label":e("profileName"),onChange:D=>b(D.target.value),disabled:ne})}):null]}),Oe?(0,V.jsx)("div",{style:c.formError,role:"alert",children:Oe}):null]}),(0,V.jsxs)("div",{style:c.formActions,children:[typeof t=="function"?(0,V.jsx)(J,{onClick:t,disabled:ne,children:e("cancel")}):null,(0,V.jsx)(J,{type:"submit",variant:"primary",onClick:me,busy:ne,disabled:ne,children:e(r?ne?"connectingAction":"profilesSaveAction":ne?"connectingAction":"connectAction")})]})]})}var ni=require("react");var gt=require("react/jsx-runtime"),Jp={read:"auditRead",write:"auditWrite",deny:"auditDeny",lock:"auditLock"};function Zp(e){try{return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}catch{return""}}function Qp(e){return String(e||"").replace(/\s+/g," ").trim()}function tc({t:e,sessionId:t,open:i,onClose:s,rootRef:r}){let n=Bt(),o=(0,ni.useRef)(null),[l,h]=(0,ni.useState)(!1),[a,u]=(0,ni.useState)(null);if((0,ni.useEffect)(()=>{if(!i||!t)return;let m=!1;return h(!0),u(null),pe("audit.list",{id:t,limit:100}).then(p=>{if(m)return;let _=p&&Array.isArray(p.entries)?p.entries:[];Ca(t,_)}).catch(p=>{m||u(oe(p))}).finally(()=>{m||h(!1)}),()=>{m=!0}},[i,t]),(0,ni.useEffect)(()=>{if(!i)return;let m=_=>{let g=r&&r.current;g&&_.target instanceof Node&&g.contains(_.target)||s()},p=_=>{_.key==="Escape"&&(_.stopPropagation(),typeof _.preventDefault=="function"&&_.preventDefault(),s())};return document.addEventListener("mousedown",m,!0),document.addEventListener("keydown",p,!0),()=>{document.removeEventListener("mousedown",m,!0),document.removeEventListener("keydown",p,!0)}},[i,s,r]),!i||!t)return null;let d=(n.audit[t]||[]).slice().reverse();return(0,gt.jsxs)("div",{ref:o,style:c.popover,role:"dialog","aria-label":e("audit"),children:[(0,gt.jsx)("div",{style:c.popoverHeader,children:(0,gt.jsx)("span",{style:{flex:1,minWidth:0},children:e("audit")})}),(0,gt.jsxs)("div",{style:c.auditList,children:[l&&d.length===0?(0,gt.jsx)("div",{style:c.auditEmpty,children:e("auditLoading")}):null,!l&&d.length===0?(0,gt.jsx)("div",{style:c.auditEmpty,children:e("auditEmpty")}):null,d.map((m,p)=>{let _=Jp[m.action]||"auditRead",g=m.source==="ai"?e("sourceAi"):e("sourceHuman"),y=Qp(m.detail);return(0,gt.jsxs)("div",{style:c.auditRow,title:y||void 0,children:[(0,gt.jsx)("span",{style:c.auditTime,children:Zp(m.at)}),(0,gt.jsx)("span",{style:{...c.auditBadge,color:m.source==="ai"?f.warnLabel:f.labelSecondary},children:g}),(0,gt.jsx)("span",{style:{...c.auditBadge,color:m.action==="deny"?f.danger:f.labelSecondary},children:e(_)}),(0,gt.jsx)("span",{style:c.auditDetail,children:y||"—"})]},`${m.at}-${p}`)})]}),a?(0,gt.jsx)("div",{style:{...c.formError,margin:6},children:I(e,"auditFailed",{message:a})}):null]})}var ke=require("react");var U=require("react/jsx-runtime"),e_=["0","1","2","3","4","5"];function ic({line:e}){return(0,U.jsxs)("div",{style:c.matchRow,children:[(0,U.jsx)("span",{style:c.matchTime}),(0,U.jsx)("span",{style:c.contextText,children:e})]})}function t_({match:e,pattern:t}){let i=ha(e.line,t);return(0,U.jsxs)("div",{style:c.matchRow,children:[(0,U.jsx)("span",{style:c.matchTime,children:zr(e.at)}),(0,U.jsx)("span",{style:c.matchText,children:i.map((s,r)=>s.hit?(0,U.jsx)("span",{style:c.matchHit,children:s.text},`h${r}`):(0,U.jsx)("span",{children:s.text},`p${r}`))})]})}function sc({t:e,sessionId:t,onClose:i}){let[s,r]=(0,ke.useState)([]),[n,o]=(0,ke.useState)("loading"),[l,h]=(0,ke.useState)(null),[a,u]=(0,ke.useState)(null),[d,m]=(0,ke.useState)(""),[p,_]=(0,ke.useState)(""),[g,y]=(0,ke.useState)(""),[x,j]=(0,ke.useState)("0"),[z,C]=(0,ke.useState)(null),[O,X]=(0,ke.useState)(null),[$,ye]=(0,ke.useState)({enabled:!1,dir:""}),[de,fe]=(0,ke.useState)(!1),[Z,we]=(0,ke.useState)(!0),[k,E]=(0,ke.useState)(null),[A,L]=(0,ke.useState)(""),[T,b]=(0,ke.useState)(null),[M,B]=(0,ke.useState)("idle"),[te,Se]=(0,ke.useState)(null),[ne,_e]=(0,ke.useState)(null),Oe=(0,ke.useRef)(null),se=(0,ke.useRef)(0),W=(0,ke.useRef)(!0);(0,ke.useEffect)(()=>{W.current=!0;let P=!1;return(async()=>{P||(o("loading"),h(null));try{let D=await Xo({limit:50});if(P||!W.current)return;let Y=D&&Array.isArray(D.sessions)?D.sessions.map(Ts).filter(Boolean):[];Y.sort((Ae,qe)=>(qe.lastTs||qe.createdAt)-(Ae.lastTs||Ae.createdAt)),r(Y),o(Y.length>0?"ready":"empty");let Ne=Y.find(Ae=>Ae.id===t)||Y[0];u(Ne?Ne.id:null)}catch(D){if(P||!W.current)return;h(oe(D)),o("error")}})(),()=>{P=!0,W.current=!1}},[]);async function q(P=a,me={since:d,until:p,search:g,context:x}){if(!P){B("empty"),Se(null),C(null);return}let D=Wr(me.since),Y=Wr(me.until);if(!D.ok){B("error"),Se(I(e,"historyTimeInvalid",{value:String(me.since||"").trim()}));return}if(!Y.ok){B("error"),Se(I(e,"historyTimeInvalid",{value:String(me.until||"").trim()}));return}let Ne=se.current+1;se.current=Ne,B("loading"),Se(null),X(aa(me.search));try{let Ae=await ea({sessionId:P,since:D.at,until:Y.at,search:la(me.search),context:Number(me.context)||0,maxMatches:200});if(se.current!==Ne||!W.current)return;let qe=ia(Ae);C(qe);let Ce=qe.matches.length===0?qe.text.trim():"";B(qe.matches.length>0||Ce!==""?"ready":"empty")}catch(Ae){if(se.current!==Ne||!W.current)return;Se(I(e,"historyQueryFailed",{message:oe(Ae)})),B("error"),C(null)}}(0,ke.useEffect)(()=>{a&&q(a,{since:d,until:p,search:g,context:x})},[a]);let le=P=>{if(P===a){q(P);return}u(P),C(null),B("idle"),Se(null),_e(null)},vt=z&&z.matches.length===0&&z.text.trim()!==""?z.text.replace(/\n+$/,"").split(`
|
|
386
|
-
`):[],
|
|
387
|
-
`):z.text;try{await Fs(P,Oe.current)?G(e("copied")):(_e(P),G(e("historyCopyFailed")))}catch{_e(P),G(e("historyCopyFailed"))}};(0,ke.useEffect)(()=>{let P=!1;return Zo().then(me=>{P||!me||ye({enabled:me.enabled===!0,dir:typeof me.dir=="string"?me.dir:""})}).catch(me=>{P||me&&me.code==="UNKNOWN_METHOD"&&we(!1)}),()=>{P=!0}},[]);let oi=async P=>{if(!A){L(P),b(null);try{let D=await Jo(P==="all"?{all:!0}:{sessionId:a||t||void 0});E(D||null);let Y=D&&Array.isArray(D.files)?D.files:[];G(Y.length>0?I(e,"historyExportDone",{count:Y.length}):e("historyExportEmpty"))}catch(me){me&&me.code==="UNKNOWN_METHOD"?(we(!1),b(e("historyExportNeedsRestart"))):b(oe(me))}finally{L("")}}},ft=async()=>{if(!de){fe(!0);try{let P=await Qo({enabled:!$.enabled});ye({enabled:P&&P.enabled===!0,dir:P&&typeof P.dir=="string"?P.dir:$.dir}),G(P&&P.enabled===!0?e("historyAutoLogOn"):e("historyAutoLogOff"))}catch(P){P&&P.code==="UNKNOWN_METHOD"?(we(!1),G(e("historyExportNeedsRestart"))):G(I(e,"historyAutoLogFailed",{message:oe(P)}))}finally{fe(!1)}}},bi=(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:z?`${I(e,"historyFooter",{size:li(z.scannedBytes),count:re})}${z.truncated?` · ${e("historyTruncated")}`:""}`:e("historyEmptyQuery")}),(0,U.jsx)("span",{style:c.controlSpacer}),(0,U.jsx)(J,{onClick:Ct,disabled:!ot,title:e("historyCopy"),children:e("historyCopy")}),(0,U.jsx)(J,{onClick:()=>oi("current"),busy:A==="current",disabled:A!==""||!Z,title:Z?I(e,"historyExportHint",{dir:$.dir||"~/.dsh/aiterm/exports"}):e("historyExportNeedsRestart"),children:e("historyExportOne")}),(0,U.jsx)(J,{onClick:()=>oi("all"),busy:A==="all",disabled:A!==""||!Z,title:e(Z?"historyExportAllHint":"historyExportNeedsRestart"),children:e("historyExportAll")})]});return(0,U.jsxs)(Si,{title:e("historyTitle"),onBack:i,backLabel:e("historyPanelClose"),footer:bi,children:[(0,U.jsx)("div",{style:c.sectionTitle,children:e("historySessionsTitle")}),n==="loading"?(0,U.jsx)("div",{style:c.auditEmpty,children:e("historyLoadingSessions")}):null,n==="error"?(0,U.jsx)("div",{style:c.formError,role:"alert",children:I(e,"historySessionsFailed",{message:l})}):null,n==="empty"?(0,U.jsx)("div",{style:c.auditEmpty,children:e("historySessionsEmpty")}):null,s.length>0?(0,U.jsx)("div",{style:c.listBox,role:"listbox","aria-label":e("historySessionsTitle"),children:s.map(P=>{let me=P.id===a,D=P.createdAt>0?$r(P.createdAt):"—",Y=P.closedAt?$r(P.closedAt):e("historyOngoing");return(0,U.jsxs)("button",{type:"button",role:"option","aria-selected":me,title:`${P.title} · ${P.host||P.transport}`,style:{...c.listRow,...me?c.listRowActive:null},onClick:()=>le(P.id),children:[(0,U.jsx)("span",{style:c.listRowTitle,children:P.title}),(0,U.jsx)("span",{style:c.listRowMeta,children:`${P.host||P.transport} · ${D}→${Y} · ${li(P.bytes)}`})]},P.id)})}):null,(0,U.jsxs)("div",{style:c.filterRow,children:[(0,U.jsx)(Pe,{label:e("historySince"),style:c.grow,children:(0,U.jsx)("input",{style:c.input,value:d,placeholder:"10m",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:P=>m(P.target.value),onKeyDown:P=>{P&&P.key==="Enter"&&q()}})}),(0,U.jsx)(Pe,{label:e("historyUntil"),style:c.grow,children:(0,U.jsx)("input",{style:c.input,value:p,placeholder:"",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:P=>_(P.target.value),onKeyDown:P=>{P&&P.key==="Enter"&&q()}})}),(0,U.jsx)("div",{style:{flex:"none",width:62},children:(0,U.jsx)(Pe,{label:e("historyContext"),children:(0,U.jsx)("select",{style:c.select,value:x,onChange:P=>j(P.target.value),children:e_.map(P=>(0,U.jsx)("option",{value:P,children:P},P))})})})]}),(0,U.jsx)(Pe,{label:e("historySearch"),hint:e("historySearchHint"),children:(0,U.jsx)("input",{style:c.input,value:g,placeholder:"error|timeout",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:P=>y(P.target.value),onKeyDown:P=>{P&&P.key==="Enter"&&q()}})}),(0,U.jsx)("div",{style:c.actionRow,children:(0,U.jsx)(J,{variant:"primary",onClick:()=>q(),disabled:!a||M==="loading",children:e(M==="loading"?"historyQuerying":"historyQuery")})}),M==="error"&&te?(0,U.jsx)("div",{style:c.formError,role:"alert",children:te}):null,!a&&n!=="loading"?(0,U.jsx)("div",{style:c.auditEmpty,children:e("historyNeedSession")}):null,M==="empty"&&!te?(0,U.jsxs)("div",{style:c.auditEmpty,children:[e("historyNoMatches"),(0,U.jsx)("span",{style:{display:"block",fontSize:10},children:e("historyNoMatchesHint")})]}):null,Ue?(0,U.jsx)("div",{ref:Oe,style:c.scrollArea,children:z.matches.map((P,me)=>(0,U.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:"none",padding:"2px 0",borderBottom:`0.5px solid ${f.borderL1}`},children:[P.before.map((D,Y)=>(0,U.jsx)(ic,{line:D},`b${Y}`)),(0,U.jsx)(t_,{match:P,pattern:O}),P.after.map((D,Y)=>(0,U.jsx)(ic,{line:D},`a${Y}`))]},`${P.at}-${me}`))}):null,!Ue&&vt.length>0?(0,U.jsxs)("div",{ref:Oe,style:c.scrollArea,children:[(0,U.jsx)("div",{style:c.hint,children:e("historyFragment")}),vt.map((P,me)=>(0,U.jsx)("div",{style:c.matchRow,children:(0,U.jsx)("span",{style:c.matchText,children:P})},`f${me}`))]}):null,(0,U.jsx)("div",{style:c.sectionTitle,children:e("historyLogFileTitle")}),Z?null:(0,U.jsx)("div",{style:c.hint,role:"status",children:e("historyExportNeedsRestart")}),(0,U.jsxs)("label",{style:c.checkRow,children:[(0,U.jsx)("input",{type:"checkbox",checked:$.enabled,disabled:de||!Z,onChange:()=>ft(),style:c.pickBox}),(0,U.jsx)("span",{style:c.checkLabel,children:e("historyAutoLogLabel")})]}),(0,U.jsx)("span",{style:c.hint,children:$.enabled?I(e,"historyAutoLogWhere",{dir:$.dir}):e("historyAutoLogOffHint")}),T?(0,U.jsx)("div",{style:c.formError,role:"alert",children:I(e,"historyExportFailed",{message:T})}):null,k?(0,U.jsxs)("div",{style:c.exportBox,role:"status",children:[(0,U.jsx)("div",{style:c.hint,children:I(e,"historyExportWhere",{dir:k.dir||""})}),(k.files||[]).map(P=>(0,U.jsxs)("div",{style:c.exportRow,children:[(0,U.jsx)("span",{style:c.exportPath,title:P.path,children:P.path}),(0,U.jsx)("span",{style:c.exportMeta,children:`${li(P.bytes)} · ${I(e,"historyExportLines",{count:P.lines})}`})]},P.path))]}):null,ne!==null?(0,U.jsxs)("div",{style:{flex:"none",padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1},children:[(0,U.jsx)("div",{style:c.hint,children:e("historyManualCopy")}),(0,U.jsx)("textarea",{style:c.textarea,readOnly:!0,value:ne,onFocus:P=>{try{P.target.select()}catch{}}})]}):null]})}var Ze=require("react");var Q=require("react/jsx-runtime"),Cr="__new__";function rc(e){let t=e.username?`${e.username}@`:"";return`${e.transport} ${t}${e.host}:${e.port}`}function i_({profile:e,t,busy:i,renaming:s,moving:r,confirmed:n,highlighted:o,folderOptions:l,rowRef:h,handlers:a}){let u=!!(s&&s.id===e.id),d=!!(r&&r.id===e.id),m=[];return e.hasPassword&&m.push({key:"password",label:t("profilesBadgePassword")}),e.hasPrivateKey&&m.push({key:"privateKey",label:t("profilesBadgePrivateKey")}),e.hasPassphrase&&m.push({key:"passphrase",label:t("profilesBadgePassphrase")}),(0,Q.jsxs)("div",{ref:h,"data-profile-id":e.id,style:{...c.profileRow,...o?c.profileRowHighlight:null},children:[(0,Q.jsxs)("div",{style:c.profileMain,children:[(0,Q.jsx)("span",{style:c.profileName,title:e.name,children:e.name}),(0,Q.jsx)("span",{style:c.profileAddress,title:rc(e),children:rc(e)}),m.length>0?(0,Q.jsx)("span",{style:c.profileBadges,children:m.map(p=>(0,Q.jsx)("span",{style:c.badge,children:p.label},p.key))}):null]}),u?(0,Q.jsxs)("div",{style:c.inlineRow,children:[(0,Q.jsx)("input",{style:{...c.input,width:140},value:s.value,"aria-label":t("profilesNamePlaceholder"),autoComplete:"off",spellCheck:!1,disabled:i,onChange:p=>a.onRenameInput(p.target.value),onKeyDown:p=>{p&&(p.key==="Enter"&&a.onRenameSubmit(e),p.key==="Escape"&&(p.stopPropagation(),a.onRenameCancel()))}}),(0,Q.jsx)(J,{variant:"primary",title:`${t("profilesRenameSave")} ${e.name}`,disabled:i,onClick:()=>a.onRenameSubmit(e),children:t("profilesRenameSave")}),(0,Q.jsx)(J,{title:`${t("profilesRenameCancel")} ${e.name}`,disabled:i,onClick:a.onRenameCancel,children:t("profilesRenameCancel")})]}):null,d?(0,Q.jsxs)("div",{style:c.inlineRow,children:[(0,Q.jsxs)("select",{style:{...c.select,width:120},value:r.value,"aria-label":`${t("profilesMove")} ${e.name}`,disabled:i,onChange:p=>a.onMoveInput(p.target.value),children:[(0,Q.jsx)("option",{value:"",children:t("folderNone")}),l.map(p=>(0,Q.jsx)("option",{value:p,children:p},p)),(0,Q.jsx)("option",{value:Cr,children:t("folderNew")})]}),r.value===Cr?(0,Q.jsx)("input",{style:{...c.input,width:110},value:r.folder,"aria-label":`${t("folderName")} ${e.name}`,placeholder:t("folderName"),autoComplete:"off",spellCheck:!1,disabled:i,onChange:p=>a.onMoveFolderInput(p.target.value),onKeyDown:p=>{p&&(p.key==="Enter"&&a.onMoveSubmit(e),p.key==="Escape"&&(p.stopPropagation(),a.onMoveCancel()))}}):null,(0,Q.jsx)(J,{variant:"primary",title:`${t("profilesRenameSave")} ${e.name}`,disabled:i,onClick:()=>a.onMoveSubmit(e),children:t("profilesRenameSave")}),(0,Q.jsx)(J,{title:`${t("profilesRenameCancel")} ${e.name}`,disabled:i,onClick:a.onMoveCancel,children:t("profilesRenameCancel")})]}):null,u||d?null:n?(0,Q.jsx)(ri,{message:I(t,"profilesDeletePrompt",{name:e.name}),confirmLabel:t("profilesDeleteConfirm"),cancelLabel:t("cancel"),busy:i,onConfirm:()=>a.onDeleteConfirm(e),onCancel:a.onDeleteCancel}):(0,Q.jsxs)("div",{style:c.profileActions,children:[(0,Q.jsx)(J,{variant:"primary",style:c.rowBtn,title:`${t("profilesConnect")} ${e.name}`,disabled:i,onClick:()=>a.onConnect(e),children:t("profilesConnect")}),(0,Q.jsx)(J,{style:c.rowBtn,title:`${t("profilesEdit")} ${e.name}`,disabled:i,onClick:()=>a.onEdit(e),children:t("profilesEdit")}),(0,Q.jsx)(J,{style:c.rowBtn,title:`${t("profilesRename")} ${e.name}`,disabled:i,onClick:()=>a.onRenameStart(e),children:t("profilesRename")}),(0,Q.jsx)(J,{style:c.rowBtn,title:`${t("profilesMove")} ${e.name}`,disabled:i,onClick:()=>a.onMoveStart(e),children:t("profilesMove")}),(0,Q.jsx)(J,{style:c.rowBtn,variant:"danger",title:`${t("profilesDelete")} ${e.name}`,disabled:i,onClick:()=>a.onDeleteStart(e),children:t("profilesDelete")})]})]})}function nc({t:e,onClose:t}){let s=Bt().highlightProfileId||null,[r,n]=(0,Ze.useState)([]),[o,l]=(0,Ze.useState)([]),[h,a]=(0,Ze.useState)("loading"),[u,d]=(0,Ze.useState)(null),[m,p]=(0,Ze.useState)(null),[_,g]=(0,Ze.useState)(!1),[y,x]=(0,Ze.useState)(null),[j,z]=(0,Ze.useState)(null),[C,O]=(0,Ze.useState)(null),[X,$]=(0,Ze.useState)(""),[ye,de]=(0,Ze.useState)([]),fe=(0,Ze.useRef)(!0),Z=(0,Ze.useRef)(null),we=(0,Ze.useRef)(new Map);async function k(){a("loading"),d(null);try{let W=await Ls();if(!fe.current)return;let q=As(W);n(q.profiles),l(q.folders.map(le=>le.name)),a(q.profiles.length>0?"ready":"empty")}catch(W){if(!fe.current)return;d(oe(W)),a("error")}}(0,Ze.useEffect)(()=>(fe.current=!0,k(),()=>{fe.current=!1}),[]),(0,Ze.useEffect)(()=>{if(!s)return;let W=we.current.get(s);if(W&&typeof W.scrollIntoView=="function")try{W.scrollIntoView({block:"nearest"})}catch{}},[s,r.length]);let E=[...new Set([...o,...ye,...r.map(W=>W.folder).filter(Boolean)])].sort((W,q)=>W.localeCompare(q)),A=jo(r);async function L(W){if(!_){g(!0),p(null);try{await W()}catch(q){let le=oe(q);fe.current&&(p(le),G(I(e,"profilesActionFailed",{message:le})))}finally{fe.current&&g(!1)}}}let T=W=>L(async()=>{let q=await pe("sessions.create",{profileId:W.id,transport:W.transport,host:W.host,port:W.port,username:W.username,cols:100,rows:30}),le=Yt(q&&q.session);q&&q.session&&Lt(q.session),le&&hi(le.id)}),b=W=>Ti(W),M=W=>{x(null),z(null),p(null),O(W.id)},B=()=>O(null),te=W=>{O(null),L(async()=>{await Vo(W.id),G(e("profilesDeleteDone")),await k()})},Se=W=>{let q=y&&y.id===W.id?String(y.value||"").trim():"";if(q===""){p(e("profilesNameRequired"));return}x(null),L(async()=>{await Uo(W.id,q),G(e("profilesRenamed")),await k()})},ne=W=>{if(!j||j.id!==W.id)return;let q=j.value===Cr?String(j.folder||"").trim():j.value;if(j.value===Cr&&q===""){p(e("profilesFolderNameRequired"));return}z(null),L(async()=>{await qo(W.id,q),G(e("profilesMoved")),await k()})},_e=()=>{let W=X.trim();if(W===""){p(e("profilesFolderNameRequired"));return}p(null),de(q=>q.includes(W)?q:q.concat([W])),$(""),G(I(e,"profilesFolderAdded",{name:W}))},Oe={onConnect:T,onEdit:b,onRenameStart:W=>{z(null),O(null),p(null),x({id:W.id,value:W.name})},onRenameInput:W=>x(q=>q&&{...q,value:W}),onRenameSubmit:Se,onRenameCancel:()=>x(null),onMoveStart:W=>{x(null),O(null),p(null),z({id:W.id,value:W.folder||"",folder:""})},onMoveInput:W=>z(q=>q&&{...q,value:W}),onMoveFolderInput:W=>z(q=>q&&{...q,folder:W}),onMoveSubmit:ne,onMoveCancel:()=>z(null),onDeleteStart:M,onDeleteConfirm:te,onDeleteCancel:B},se=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:I(e,"profilesFooter",{profiles:r.length,folders:E.length})}),(0,Q.jsx)("span",{style:c.controlSpacer}),(0,Q.jsx)(J,{onClick:k,disabled:_||h==="loading",children:e("profilesReload")})]});return(0,Q.jsxs)(Si,{title:e("profilesTitle"),onBack:typeof t=="function"?t:void 0,backLabel:e("profilesPanelClose"),actions:(0,Q.jsx)(J,{variant:"primary",onClick:()=>Ti(),disabled:_,children:e("profilesNewConnection")}),footer:se,children:[(0,Q.jsxs)("div",{style:c.folderPickerRow,children:[(0,Q.jsx)(Pe,{label:e("profilesNewFolder"),style:c.grow,children:(0,Q.jsx)("input",{style:c.input,value:X,placeholder:e("profilesNewFolderPlaceholder"),"aria-label":e("profilesNewFolderPlaceholder"),autoComplete:"off",spellCheck:!1,disabled:_,onChange:W=>$(W.target.value),onKeyDown:W=>{W&&W.key==="Enter"&&_e()}})}),(0,Q.jsx)(J,{onClick:_e,disabled:_||X.trim()==="",title:e("profilesCreateFolder"),children:e("profilesCreateFolder")})]}),m?(0,Q.jsx)("div",{style:c.formError,role:"alert",children:m}):null,h==="loading"&&r.length===0?(0,Q.jsx)("div",{style:c.auditEmpty,children:e("profilesLoading")}):null,h==="error"?(0,Q.jsx)("div",{style:c.formError,role:"alert",children:I(e,"profilesListFailed",{message:u||""})}):null,h==="empty"?(0,Q.jsxs)("div",{style:c.stateWrap,children:[(0,Q.jsx)("p",{style:c.stateTitle,children:e("profilesEmpty")}),(0,Q.jsx)("p",{style:c.stateDetail,children:e("profilesEmptyHint")}),(0,Q.jsx)(J,{variant:"primary",onClick:()=>Ti(),disabled:_,children:e("profilesNewConnection")})]}):null,r.length>0?(0,Q.jsx)("div",{ref:Z,style:c.profileList,role:"list","aria-label":e("profilesTitle"),children:A.map(W=>(0,Q.jsxs)("div",{style:c.profileSection,children:[(0,Q.jsxs)("div",{style:c.profileSectionHeader,children:[(0,Q.jsx)("span",{children:W.folder||e("profilesUngrouped")}),(0,Q.jsx)("span",{style:c.profileCount,children:I(e,"profilesFolderCount",{count:W.count})})]}),W.items.map(q=>(0,Q.jsx)(i_,{profile:q,t:e,busy:_,renaming:y,moving:j,confirmed:C===q.id,highlighted:s===q.id,folderOptions:E,rowRef:le=>{le?we.current.set(q.id,le):we.current.delete(q.id)},handlers:Oe},q.id))]},W.folder||"__ungrouped"))}):null]})}var ve=require("react");var ac=["send","delay","set","log","expect","if","loop"];var s_=/^[A-Za-z_][A-Za-z0-9_]{0,31}$/,Co=[{id:"send",labelKey:"tplSend",make:()=>({send:"uptime",enter:!0})},{id:"delay",labelKey:"tplDelay",make:()=>({delay:1e3})},{id:"set",labelKey:"tplSet",make:()=>({set:"target",value:"world"})},{id:"if",labelKey:"tplIf",make:()=>({if:{contains:"error"},then:[{log:'matched "error"'}],else:[{log:"no error seen"}]})},{id:"loop",labelKey:"tplLoop",make:()=>({loop:{count:3,maxIterations:10},steps:[{send:"echo tick",enter:!0},{delay:200}]})},{id:"expect",labelKey:"tplExpect",make:()=>({expect:{match:"ok"},onFail:"stop"})},{id:"log",labelKey:"tplLog",make:()=>({log:"note"})}];function lc(e){return typeof e!="string"||e===""||!ac.includes(e)?"kindUnknown":`kind${e.charAt(0).toUpperCase()}${e.slice(1)}`}function hc(e,t){let i=Co.find(h=>h.id===t),s=typeof e=="string"?e:"";if(!i)return{ok:!1,text:s,rebuilt:!1};let r=null,n=!1;if(s.trim()!=="")try{let h=JSON.parse(s);h&&typeof h=="object"&&!Array.isArray(h)?r=h:n=!0}catch{n=!0}r||(r={name:"",description:"",params:{},steps:[]}),Array.isArray(r.steps)||(r.steps=[],n=!0);let o;try{o=i.make()}catch{return{ok:!1,text:s,rebuilt:n}}let l={...r,steps:r.steps.concat([o])};try{return{ok:!0,text:JSON.stringify(l,null,2),rebuilt:n}}catch{return{ok:!1,text:s,rebuilt:n}}}function bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function r_(e){return ac.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Ni(e,t,i,s=0){if(s>8){i.push({path:t,key:"vConditionDeep",params:{max:8}});return}let r=bs(e);if(!r){i.push({path:t,key:"vCondition"});return}let n=["always","match","contains","variable","not","all","any"].filter(l=>Object.prototype.hasOwnProperty.call(r,l));if(n.length!==1){i.push({path:t,key:"vCondition"});return}let o=n[0];if(o==="always"){r.always!==!0&&i.push({path:t,key:"vCondition"});return}if(o==="match"||o==="contains"){if(typeof r[o]!="string"||r[o]===""){i.push({path:t,key:"vCondition"});return}o==="match"&&!oc(r.match)&&i.push({path:`${t}.match`,key:"vConditionRegex"});return}if(o==="variable"){(typeof r.variable!="string"||r.variable==="")&&i.push({path:t,key:"vCondition"});for(let l of["equals","notEquals","contains","matches"])r[l]!==void 0&&typeof r[l]!="string"&&i.push({path:t,key:"vCondition"});typeof r.matches=="string"&&r.matches!==""&&!oc(r.matches)&&i.push({path:`${t}.matches`,key:"vConditionRegex"});return}if(o==="not"){Ni(r.not,`${t}.not`,i,s+1);return}if(!Array.isArray(r[o])||r[o].length===0){i.push({path:t,key:"vConditionList",params:{key:o}});return}r[o].forEach((l,h)=>{Ni(l,`${t}.${o}[${h}]`,i,s+1)})}function oc(e){try{return new RegExp(e),!0}catch{return!1}}function xr(e,t,i,s,r){if(!Array.isArray(e)){s.push({path:t,key:"vSteps"});return}if(i>5){s.push({path:t,key:"vTooDeep",params:{max:5}});return}e.forEach((n,o)=>{r.total+=1,r.total>500&&!r.flagged&&(r.flagged=!0,s.push({path:t,key:"vTooMany",params:{max:500}})),n_(n,`${t}[${o}]`,i,s,r)})}function n_(e,t,i,s,r){let n=bs(e);if(!n){s.push({path:t,key:"vStepObject"});return}let o=r_(n);if(o.length===0){let a=Object.keys(n);a.length===0?s.push({path:t,key:"vNoKind"}):s.push({path:t,key:"vUnknownKind",params:{kind:a.join("/")}});return}if(o.length>1){s.push({path:t,key:"vMultiKind",params:{kinds:o.join("/")}});return}let l=o[0];if(l==="send"){(typeof n.send!="string"||n.send.trim()==="")&&s.push({path:t,key:"vSend"});return}if(l==="delay"){(typeof n.delay!="number"||!Number.isFinite(n.delay)||n.delay<=0)&&s.push({path:t,key:"vDelay"});return}if(l==="set"){(typeof n.set!="string"||!s_.test(n.set))&&s.push({path:t,key:"vSetName"}),typeof n.value!="string"&&s.push({path:t,key:"vSetValue"});return}if(l==="log"){typeof n.log!="string"&&s.push({path:t,key:"vLog"});return}if(l==="expect"){bs(n.expect)?Ni(n.expect,`${t}.expect`,s):s.push({path:t,key:"vExpect"}),n.onFail!==void 0&&n.onFail!=="stop"&&n.onFail!=="continue"&&s.push({path:t,key:"vExpectOnFail"});return}if(l==="if"){Ni(n.if,`${t}.if`,s),Array.isArray(n.then)?n.then.length===0?s.push({path:t,key:"vIfThenEmpty"}):xr(n.then,`${t}.then`,i+1,s,r):s.push({path:t,key:"vIfThen"}),n.else!==void 0&&(Array.isArray(n.else)?xr(n.else,`${t}.else`,i+1,s,r):s.push({path:t,key:"vIfElse"}));return}let h=bs(n.loop);if(!h)s.push({path:t,key:"vLoopCond"});else{let a=h.count!==void 0,u=h.while!==void 0,d=h.until!==void 0;!a&&!u&&!d&&s.push({path:t,key:"vLoopCond"}),a&&(!Number.isInteger(h.count)||h.count<1||h.count>1e3)&&s.push({path:`${t}.loop.count`,key:"vLoopCount",params:{max:1e3}}),u&&Ni(h.while,`${t}.loop.while`,s),d&&Ni(h.until,`${t}.loop.until`,s),h.maxIterations!==void 0&&(!Number.isInteger(h.maxIterations)||h.maxIterations<1||h.maxIterations>1e3)&&s.push({path:`${t}.loop.maxIterations`,key:"vLoopMax",params:{max:1e3}})}!Array.isArray(n.steps)||n.steps.length===0?s.push({path:t,key:"vLoopBody"}):xr(n.steps,`${t}.steps`,i+1,s,r)}function cc(e){let t=bs(e);if(!t)return[{path:"script",key:"vSteps"}];if(!Array.isArray(t.steps))return[{path:"steps",key:"vSteps"}];let i=[],s={total:0,flagged:!1};return xr(t.steps,"steps",0,i,s),i}var o_=new Set(["raw","wait","set","log","expect","python","end"]);function a_(e){let t=/^(\d+(?:\.\d+)?)\s*(ms|s)?$/i.exec(String(e||"").trim());if(!t)return null;let i=Number(t[1]);if(!Number.isFinite(i)||i<0)return null;let s=(t[2]||"ms").toLowerCase();return Math.round(s==="s"?i*1e3:i)}function dc(e,t={}){let i=t.waitAfterSend===!0,s=Number.isInteger(t.idleMs)?t.idleMs:250,r=Number.isInteger(t.timeoutMs)?t.timeoutMs:15e3,n=[],o=String(e??"").split(/\r?\n/),l=null,h=(a,u)=>{let d={send:a,enter:u};return i&&u&&(d.waitFor={idleMs:s,timeoutMs:r}),d};for(let a=0;a<o.length;a+=1){let u=o[a],d=u.trim(),m=a+1;if(l!==null){if(d==="@end"){n.push({send:"PY",enter:!0}),l=null;continue}d.length>0&&n.push({send:u,enter:!0});continue}if(d.length===0||d.startsWith("#"))continue;if(!d.startsWith("@")){n.push(h(d,!0));continue}let p=/^@([a-zA-Z]+)\s*([\s\S]*)$/.exec(d),_=p?p[1].toLowerCase():"",g=p?p[2].trim():"";if(!o_.has(_))return{ok:!1,line:m,message:`unknown directive @${_||"?"}`};if(_==="python"){n.push({send:"python3 - <<'PY'",enter:!0}),l={opened:!0};continue}if(_==="end")return{ok:!1,line:m,message:"@end without @python"};if(_==="raw"){if(g.length===0)return{ok:!1,line:m,message:"@raw needs text"};n.push({send:g,enter:!1});continue}if(_==="wait"){let x=a_(g);if(x===null)return{ok:!1,line:m,message:"@wait needs a duration, e.g. @wait 500 or @wait 2s"};n.push({delay:x});continue}if(_==="set"){let x=/^([A-Za-z][A-Za-z0-9_]*)\s*(?:=|\s)\s*([\s\S]*)$/.exec(g);if(!x)return{ok:!1,line:m,message:'@set needs "name = value"'};n.push({set:x[1],value:x[2].trim()});continue}if(_==="log"){if(g.length===0)return{ok:!1,line:m,message:"@log needs text"};n.push({log:g});continue}let y=/^(continue\s+)?([\s\S]+)$/.exec(g);if(!y||y[2].trim().length===0)return{ok:!1,line:m,message:"@expect needs a pattern"};n.push({expect:{match:y[2].trim()},onFail:y[1]?"continue":"stop"})}return l!==null?{ok:!1,line:o.length,message:"@python block is missing @end"}:n.length===0?{ok:!1,line:1,message:"the script has no steps"}:{ok:!0,steps:n}}function uc(e){if(!Array.isArray(e)||e.length===0)return{ok:!1,reason:"empty"};let t=[],i=null,s=!0;for(let n of e){if(n===null||typeof n!="object")return{ok:!1,reason:"invalid"};if(typeof n.send=="string"){let o=n.waitFor;if(o===void 0)s=!1;else{let l=`${o.idleMs===void 0?"":o.idleMs}/${o.timeoutMs===void 0?"":o.timeoutMs}`;if(i===null)i=l;else if(i!==l)return{ok:!1,reason:"mixedWait"}}if(n.read!==void 0&&n.read!=="delta")return{ok:!1,reason:"read"};if(n.capture!==void 0)return{ok:!1,reason:"capture"};t.push(n.enter===!1?`@raw ${n.send}`:n.send);continue}if(Number.isInteger(n.delay)){t.push(`@wait ${n.delay}`);continue}if(typeof n.set=="string"){t.push(`@set ${n.set} = ${n.value===void 0?"":n.value}`);continue}if(typeof n.log=="string"){t.push(`@log ${n.log}`);continue}if(n.expect!==void 0){if(typeof n.expect.match!="string")return{ok:!1,reason:"condition"};if(n.capture!==void 0)return{ok:!1,reason:"capture"};t.push(`@expect ${n.onFail==="continue"?"continue ":""}${n.expect.match}`);continue}return{ok:!1,reason:"structured"}}let r=s&&i!==null;return{ok:!0,text:t.join(`
|
|
388
|
-
`),waitAfterSend:r}}var
|
|
385
|
+
`;var Qi=require("react/jsx-runtime"),Kp=32768,jc=8192;function Yc({t:e,session:t,onLinkChange:i,reset:s}){let r=(0,Ct.useRef)(null),n=(0,Ct.useRef)(null),o=(0,Ct.useRef)(typeof e=="function"?e:g=>g),l=(0,Ct.useRef)(t),c=(0,Ct.useRef)(i),[a,u]=(0,Ct.useState)(null),d=(0,Ct.useRef)(Fr(s&&s.seq?s.seq:0));o.current=typeof e=="function"?e:g=>g,l.current=t,c.current=i;let _=!!t.permission.humanWriteBlocked,m=t.state==="closed"||t.state==="failed",p=t.state==="disconnected";return(0,Ct.useEffect)(()=>{let g=r.current;if(!g)return;let y=!1,x=null,q=0,W=0,k=null,M=null,Z=null,K=null,ye=null,ce={text:"",busy:!1},he=()=>l.current,G=()=>o.current,ke=T=>{if(!y)try{c.current?.(T)}catch(w){console.error("[aiterm] link reporter failed",w)}},R=()=>{if(ce.busy||ce.text===""||y)return;let T=he();if(T.state!=="open"||T.permission.humanWriteBlocked){ce.text="";return}let w=ce.text.slice(0,jc);ce.text=ce.text.slice(jc),ce.busy=!0,ge("sessions.input",{id:he().id,data:w}).catch(I=>{if(y)return;let P=I&&typeof I.code=="string"?I.code:"";if(P==="HUMAN_WRITE_BLOCKED"){ce.text="",J(D(G(),"blockedTitle"));return}(P==="NOT_CONNECTED"||P==="SESSION_NOT_FOUND"||P==="WRITE_FAILED"||P==="INPUT_TOO_LARGE")&&(ce.text=""),J(D(G(),"inputFailed",{message:ne(I)}))}).finally(()=>{ce.busy=!1,y||R()})},E=()=>{if(!(y||!ye||!K))try{if(g.clientWidth<24||g.clientHeight<24)return;ye.fit(),mn(he().id,K.cols,K.rows)}catch{}},B=()=>{y||(W&&cancelAnimationFrame(W),W=requestAnimationFrame(()=>{W=0,E()}))};try{K=new $c(qc({cols:Math.max(20,Number(he().cols)||80),rows:Math.max(5,Number(he().rows)||24),disableStdin:!!he().permission.humanWriteBlocked||he().state!=="open"})),ye=new Kc,K.loadAddon(ye),K.open(g),n.current=K}catch(T){console.error("[aiterm] terminal failed to open",T),u(ne(T)),ke("error");return}return M=K.onData(T=>{if(y||!T)return;let w=he();if(w.state==="open"&&!w.permission.humanWriteBlocked){if(ce.text.length+T.length>Kp){ce.text="",J(D(G(),"inputOverflow"));return}ce.text+=T,queueMicrotask(R)}}),Z=K.onResize(({cols:T,rows:w})=>{y||(mn(he().id,T,w),q&&clearTimeout(q),q=window.setTimeout(()=>{q=0,!y&&ge("sessions.resize",{id:he().id,cols:T,rows:w}).catch(()=>{})},250))}),typeof ResizeObserver<"u"&&(k=new ResizeObserver(B),k.observe(g)),B(),(()=>{let T;try{let w=Zr(),I=w===void 0?"":"&owner="+encodeURIComponent(w);T=new EventSource(as+"/events?sessionId="+encodeURIComponent(he().id)+I)}catch(w){console.error("[aiterm] event stream failed",w),ke("error");return}x=T,ke("connecting"),T.onopen=()=>{y||ke("open")},T.onerror=()=>{if(y)return;let w=he();if(w.state==="closed"||w.state==="failed"){try{T.close()}catch{}ke("closed");return}ke("error")},T.onmessage=w=>{if(y)return;let I=Gs(w.data);if(I)try{if(I.type==="hello"){if(!K)return;K.reset();let P=Ys(I.replay);if(P.length>0?K.write(P):ge("sessions.replay",{id:he().id}).then(re=>{if(y||!K)return;let Re=Ys(re&&re.replay);Re.length>0&&K.write(Re)}).catch(()=>{}),I.session){$t(I.session);let re=Aa(he().id);re&&re.seq&&d.current.markApplied(re.seq)}ke("open"),B()}else if(I.type==="data"){if(!K||typeof I.chunk!="string"||I.chunk==="")return;let P=Ys(I.chunk);P.length>0&&K.write(P)}else if(I.type==="reset")_n(I);else if(I.type==="state")$t(I.session);else if(I.type==="exit"){let P=typeof I.code=="number"?I.code:null;qi(he().id,typeof I.reason=="string"?I.reason:void 0),ke("closed"),J(P===null?G()("sessionEnded"):D(G(),"sessionExited",{code:P}));try{T.close()}catch{}x===T&&(x=null)}else I.type==="audit"&&Ha(he().id,I.entry)}catch(P){console.error("[aiterm] terminal frame failed",P)}}})(),()=>{y=!0,q&&clearTimeout(q),W&&cancelAnimationFrame(W);try{k?.disconnect()}catch{}try{x?.close()}catch{}try{M?.dispose()}catch{}try{Z?.dispose()}catch{}try{K?.dispose()}catch{}n.current=null}},[t.id]),(0,Ct.useEffect)(()=>{let g=n.current;if(g)try{g.options.disableStdin=_||m||t.state!=="open",(_||t.state!=="open")&&g.blur()}catch(y){console.error("[aiterm] could not update stdin gate",y)}},[_,m,t.state]),(0,Ct.useEffect)(()=>{let g=n.current,y=s&&s.seq?s.seq:0;if(!(!g||!y))try{if(!Hr(g,o.current,y,d.current))return;try{g.scrollToBottom()}catch{}}catch(x){console.error("[aiterm] could not clear the screen after a reconnect",x)}},[s?s.seq:0,t.id]),(0,Ct.useEffect)(()=>{if(typeof MutationObserver>"u"||typeof document>"u")return;let g=()=>{let q=n.current;if(q)try{q.options.theme=Ho()}catch{}},y=new MutationObserver(g),x={attributes:!0,attributeFilter:["class","style","data-theme","data-color-scheme"]};try{y.observe(document.documentElement,x),document.body&&y.observe(document.body,x)}catch{}return()=>{try{y.disconnect()}catch{}}},[]),(0,Qi.jsxs)("div",{style:{display:"flex",flex:1,minWidth:0,minHeight:0,position:"relative"},children:[(0,Qi.jsx)("style",{children:Uc+Vc}),(0,Qi.jsx)("div",{ref:r,className:"dsst-term-host",title:p?D(o.current,"disconnectedHint"):void 0}),a?(0,Qi.jsx)("div",{role:"alert",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:12,textAlign:"center",color:f.danger,fontSize:11,lineHeight:1.5,background:f.bgBase},children:D(o.current,"connectFailed",{message:a})}):null]})}var Vt=require("react");var Ni=require("react");var H=require("react/jsx-runtime");function Ns(){let[e,t]=(0,Ni.useState)(!1);return{focus:e,focusProps:{onFocus(s){let r=!1;try{let n=s&&s.currentTarget;r=typeof n.matches=="function"?n.matches(":focus-visible"):!1}catch{r=!1}t(r)},onBlur(){t(!1)}}}}var Up={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,flex:"none",height:32,padding:"0 12px",border:"0.5px solid transparent",borderRadius:f.radiusSm,background:"transparent",color:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function qp(e,t,i){return e==="primary"?{background:t?f.primaryHover:f.primaryFill,color:f.labelForeground,borderColor:f.primaryFill}:e==="danger"?{background:t?f.hoverDanger:"transparent",color:f.danger,borderColor:t?f.borderL2:"transparent"}:e==="outline"?{background:t?f.hover:"transparent",borderColor:f.borderL2,color:f.labelPrimary}:{background:t||i?f.hover:"transparent",color:t||i?f.labelPrimary:f.labelSecondary,borderColor:"transparent"}}function Q({children:e,onClick:t,variant:i="default",disabled:s=!1,busy:r=!1,title:n,ariaLabel:o,style:l}){let[c,a]=(0,Ni.useState)(!1),{focus:u,focusProps:d}=Ns(),_=s||r;return(0,H.jsx)("button",{type:"button",title:n,"aria-label":o,"aria-busy":r||void 0,disabled:_,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),...d,onClick:m=>{if(!(_||typeof t!="function"))try{let p=t(m);p&&typeof p.catch=="function"&&p.catch(()=>{})}catch(p){console.error("[aiterm] button action failed",p)}},style:{...Up,...qp(i,c&&!_),..._?{opacity:.45,cursor:"default"}:null,boxShadow:Zi(u),...l},children:r?"…":e})}function qt({children:e,onClick:t,title:i,ariaLabel:s,active:r=!1,danger:n=!1,disabled:o=!1,size:l=30}){let[c,a]=(0,Ni.useState)(!1),{focus:u,focusProps:d}=Ns();return(0,H.jsx)("button",{type:"button",title:i,"aria-label":s||i,"aria-pressed":r,disabled:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),...d,onClick:_=>{if(!(o||typeof t!="function"))try{let m=t(_);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch(m){console.error("[aiterm] icon action failed",m)}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:l,height:l,padding:0,border:"0.5px solid transparent",borderRadius:f.radiusSm,background:c&&!o?n?f.hoverDanger:f.hover:"transparent",color:n?f.danger:c&&!o?f.labelPrimary:f.labelSecondary,font:"inherit",fontSize:13,lineHeight:1,cursor:o?"default":"pointer",outline:"none",opacity:o?.45:1,boxShadow:Zi(u)},children:e})}function Wr({options:e,value:t,onChange:i,disabled:s=!1,label:r}){return(0,H.jsx)("div",{role:"group","aria-label":r,style:{display:"inline-flex",alignItems:"stretch",flex:"none",height:30,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,overflow:"hidden"},children:e.map((n,o)=>(0,H.jsx)(Vp,{option:n,active:n.value===t,disabled:s,last:o===e.length-1,onSelect:()=>{!s&&n.value!==t&&i(n.value)}},n.value))})}function Vp({option:e,active:t,disabled:i,last:s,onSelect:r}){let[n,o]=(0,Ni.useState)(!1),{focus:l,focusProps:c}=Ns();return(0,H.jsx)("button",{type:"button",role:"button","aria-pressed":t,title:e.hint,disabled:i,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),...c,onClick:r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:42,height:"100%",padding:"0 10px",border:0,borderRight:s?0:`0.5px solid ${f.borderL2}`,background:t?f.bgLayer3:n&&!i?f.hover:"transparent",color:i?f.labelTertiary:t?f.labelPrimary:f.labelSecondary,font:"inherit",fontSize:12,lineHeight:1,fontWeight:t?600:400,cursor:i?"default":"pointer",outline:"none",boxShadow:Zi(l),opacity:i?.5:1},children:e.label})}function Gc({state:e}){if(e==="disconnected")return(0,H.jsx)("span",{"aria-hidden":"true",style:{flex:"none",width:6,height:6,boxSizing:"border-box",borderRadius:"50%",border:`1px solid ${f.warn}`,background:"transparent"}});let t=e==="open"?f.success:e==="failed"?f.danger:e==="connecting"?f.warn:f.labelTertiary;return(0,H.jsx)("span",{"aria-hidden":"true",style:{flex:"none",width:6,height:6,borderRadius:"50%",background:t,opacity:e==="closed"?.6:1}})}function Fe({label:e,hint:t,children:i,style:s}){return(0,H.jsxs)("label",{style:{...h.field,...s},children:[(0,H.jsx)("span",{style:h.label,children:e}),i,t?(0,H.jsx)("span",{style:h.hint,children:t}):null]})}function Wo({toast:e}){return!e||!e.text?null:(0,H.jsx)("div",{role:"status","aria-live":"polite",style:h.toast,children:e.text})}function zo({title:e,hint:t,onBack:i,backLabel:s,onClose:r,closeLabel:n,actions:o}){return(0,H.jsxs)("div",{style:h.viewHeader,children:[i?(0,H.jsx)(qt,{title:s||e,onClick:i,children:(0,H.jsx)(jp,{})}):null,(0,H.jsxs)("div",{style:h.viewHeaderText,children:[(0,H.jsx)("span",{style:h.viewHeaderTitle,title:e,children:e}),t?(0,H.jsx)("span",{style:h.viewHeaderHint,children:t}):null]}),o?(0,H.jsx)("div",{style:h.viewHeaderActions,children:o}):null,r?(0,H.jsx)(qt,{title:n||e,onClick:r,children:(0,H.jsx)(Fs,{})}):null]})}function vi({message:e,confirmLabel:t,cancelLabel:i,onConfirm:s,onCancel:r,busy:n=!1,danger:o=!0}){return(0,H.jsxs)("div",{style:h.inlineConfirm,role:"alertdialog","aria-label":e,onKeyDown:l=>{l&&l.key==="Escape"&&(l.stopPropagation(),!n&&typeof r=="function"&&r())},children:[(0,H.jsx)("span",{style:h.inlineConfirmText,title:e,children:e}),(0,H.jsx)(Q,{variant:o?"danger":"primary",busy:n,disabled:n,onClick:s,children:t}),(0,H.jsx)(Q,{disabled:n,onClick:r,children:i})]})}function Fi({title:e,onBack:t,backLabel:i,onClose:s,closeLabel:r,actions:n,children:o,footer:l}){return(0,H.jsxs)("div",{style:h.sheet,role:"dialog","aria-modal":"true","aria-label":e,children:[(0,H.jsx)(zo,{title:e,onBack:t,backLabel:i,onClose:s,closeLabel:r,actions:n}),(0,H.jsx)("div",{style:h.sheetBody,children:o}),l!=null?(0,H.jsx)("div",{style:h.sheetFooter,children:l}):null]})}function Xc({title:e,onClose:t,closeLabel:i,children:s}){return(0,Ni.useEffect)(()=>{if(typeof document>"u"||typeof document.addEventListener!="function")return;let r=n=>{!n||n.key!=="Escape"||(n.stopPropagation(),typeof n.preventDefault=="function"&&n.preventDefault(),typeof t=="function"&&t())};return document.addEventListener("keydown",r,!0),()=>{try{document.removeEventListener("keydown",r,!0)}catch{}}},[t]),(0,H.jsxs)("div",{style:h.overlayWindow,role:"dialog","aria-modal":"false","aria-label":e,children:[(0,H.jsxs)("div",{style:h.overlayWindowHead,children:[(0,H.jsx)("span",{style:h.overlayWindowTitle,title:e,children:e}),(0,H.jsx)("span",{style:h.controlSpacer}),(0,H.jsx)(qt,{title:i||e,onClick:t,children:(0,H.jsx)(Fs,{})})]}),(0,H.jsx)("div",{style:h.overlayWindowBody,children:s})]})}var Ft=(e,t,i)=>(0,H.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",style:{flex:"none",...i},children:t});function jp({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M9.8 3.6 5.4 8l4.4 4.4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),(0,H.jsx)("path",{d:"M5.6 8h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]}))}function Jc({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M2.5 4.5 6 8l-3.5 3.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,H.jsx)("path",{d:"M8.5 11.5h5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}function Zc({size:e=15}){return Ft(e,(0,H.jsx)(H.Fragment,{children:(0,H.jsx)("path",{d:"M8 3.5v9M3.5 8h9",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})}))}function Fs({size:e=14}){return Ft(e,(0,H.jsx)("path",{d:"m4 4 8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}))}function Qc({size:e=15}){return Ft(e,(0,H.jsx)(H.Fragment,{children:(0,H.jsx)("path",{d:"M3 4h10M3 8h10M3 12h6",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})}))}function $o({size:e=13}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("rect",{x:"3.5",y:"7",width:"9",height:"6",rx:"1.2",stroke:"currentColor",strokeWidth:"1.1"}),(0,H.jsx)("path",{d:"M5.5 7V5.4a2.5 2.5 0 0 1 5 0V7",stroke:"currentColor",strokeWidth:"1.1"})]}))}function eh({size:e=12,open:t=!1}){return(0,H.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",style:{flex:"none",transform:t?"rotate(180deg)":"none"},children:(0,H.jsx)("path",{d:"m4 6 4 4 4-4",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function th({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("circle",{cx:"8",cy:"8",r:"5.4",stroke:"currentColor",strokeWidth:"1.1"}),(0,H.jsx)("path",{d:"M8 4.8V8l2.2 1.6",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})]}))}function ih({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M4 2.6h5.2L12 5.4v8H4z",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"}),(0,H.jsx)("path",{d:"M6 7.4h4M6 9.8h4",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round"})]}))}function sh({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M2.4 4.4a1 1 0 0 1 1-1h3l1.2 1.4h4.9a1 1 0 0 1 1 1v6.8a1 1 0 0 1-1 1H3.4a1 1 0 0 1-1-1z",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"}),(0,H.jsx)("path",{d:"M5.6 9.2h4.8",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round"})]}))}function rh({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("rect",{x:"5.4",y:"5.4",width:"7",height:"7",rx:"1.1",stroke:"currentColor",strokeWidth:"1.1"}),(0,H.jsx)("path",{d:"M10.4 5.4V4.2A1.2 1.2 0 0 0 9.2 3H4.2A1.2 1.2 0 0 0 3 4.2v5a1.2 1.2 0 0 0 1.2 1.2h1.2",stroke:"currentColor",strokeWidth:"1.1",strokeLinejoin:"round"})]}))}function nh({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M8 2.8v5.4",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),(0,H.jsx)("path",{d:"M4.6 5.2a4.4 4.4 0 1 0 6.8 0",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}function oh({size:e=15}){return Ft(e,(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)("path",{d:"M13 5.6V2.8m0 2.8H10.2",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,H.jsx)("path",{d:"M12.6 8a4.6 4.6 0 1 1-1.4-3.3",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]}))}var ah="dsh.aiterm.scriptOrder";function Hs(){try{let e=globalThis.localStorage&&globalThis.localStorage.getItem(ah);if(!e)return{};let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function zr(e){try{if(!globalThis.localStorage)return;globalThis.localStorage.setItem(ah,JSON.stringify(e))}catch{}}function es(e,t){let i=Array.isArray(t)?t.filter(o=>typeof o=="string"&&o!==""):[],s=Hs(),r=Array.isArray(s[e])?s[e].filter(o=>i.includes(o)):[],n=i.filter(o=>!r.includes(o));return r.concat(n)}function lh(e,t,i,s){let r=es(e,t),n=r.indexOf(i);if(n<0)return{names:r,moved:!1};let o=n+(s<0?-1:1);if(o<0||o>=r.length)return{names:r,moved:!1};let l=r.slice();l[n]=r[o],l[o]=r[n];let c=Hs();return c[e]=l,zr(c),{names:l,moved:!0}}function ch(e,t){let i=Hs(),s=Array.isArray(i[e])?i[e]:[];s.includes(t)&&(i[e]=s.filter(r=>r!==t),zr(i))}function hh(e,t){let i=Hs();Array.isArray(i[e])&&(i[t]=i[e],delete i[e],zr(i))}function dh(e){let t=Hs();Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],zr(t))}var He=require("react/jsx-runtime"),Yp=200,uh="dsh.aiterm.quickHiddenFolders";function Gp(){try{let e=globalThis.localStorage&&globalThis.localStorage.getItem(uh);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(i=>typeof i=="string"):[]}catch{return[]}}function Xp(e){try{if(!globalThis.localStorage)return;globalThis.localStorage.setItem(uh,JSON.stringify(e))}catch{}}function Jp(e){let t=new Map;for(let s of e){let r=s.folder||"";t.has(r)||t.set(r,[]),t.get(r).push(s)}return[...t.keys()].sort((s,r)=>s===""?1:r===""?-1:s.localeCompare(r)).map(s=>{let r=t.get(s),n=es(s,r.map(o=>o.name));return{folder:s,items:n.map(o=>r.find(l=>l.name===o)).filter(Boolean)}})}function fh({t:e,sessionId:t,open:i,onToggle:s,onOpenLibrary:r}){let[n,o]=(0,Vt.useState)([]),[l,c]=(0,Vt.useState)("idle"),[a,u]=(0,Vt.useState)(null),[d,_]=(0,Vt.useState)(()=>Gp()),[m,p]=(0,Vt.useState)(!1),g=(0,Vt.useRef)(!0);(0,Vt.useEffect)(()=>(g.current=!0,()=>{g.current=!1}),[]),(0,Vt.useEffect)(()=>{if(!i)return;let k=!1;return c(M=>M==="idle"?"loading":M),Qs().then(M=>{if(k||!g.current)return;let Z=(M&&Array.isArray(M.scripts)?M.scripts:[]).map($i).filter(Boolean);o(Jp(Z.slice(0,Yp))),c(Z.length===0?"empty":"ready")}).catch(()=>{k||!g.current||c("error")}),()=>{k=!0}},[i]);let y=n.map(k=>k.folder),x=n.filter(k=>!d.includes(k.folder)),q=k=>{let M=d.includes(k)?d.filter(Z=>Z!==k):[...d,k];_(M),Xp(M)},W=async k=>{if(a===null){if(!t){J(e("quickScriptsNoSession"));return}u(k.name);try{let M=await ir({name:k.name,params:{},sessionId:t}),K=(M&&M.result&&Array.isArray(M.result.runs)?M.result.runs:[]).filter(ye=>ye&&ye.ok===!1).length;J(K>0?D(e,"quickScriptsPartial",{name:k.name,failed:K}):D(e,"quickScriptsDone",{name:k.name}))}catch(M){J(D(e,"quickScriptsFailed",{name:k.name,message:ne(M)}))}finally{g.current&&u(null)}}};return i?(0,He.jsxs)("div",{style:h.quickBar,role:"toolbar","aria-label":e("quickScripts"),children:[(0,He.jsxs)("div",{style:h.quickBarHead,children:[(0,He.jsx)("span",{style:h.quickBarTitle,children:e("quickScripts")}),(0,He.jsx)("span",{style:h.controlSpacer}),l==="loading"?(0,He.jsx)("span",{style:h.hint,children:e("loading")}):null,l==="error"?(0,He.jsx)("span",{style:h.hint,children:e("quickScriptsLoadFailed")}):null,(0,He.jsx)(Q,{active:m,onClick:()=>p(k=>!k),title:e("quickFolderVisibility"),children:e("quickFolderVisibility")}),(0,He.jsx)(Q,{onClick:r,title:e("scriptsTitle"),children:e("quickScriptsManage")}),(0,He.jsx)(Q,{onClick:s,title:e("quickScriptsHide"),children:e("quickScriptsHide")})]}),m?(0,He.jsxs)("div",{style:h.quickBarRow,role:"group","aria-label":e("quickFolderVisibility"),children:[y.length===0?(0,He.jsx)("span",{style:h.hint,children:e("quickScriptsEmpty")}):null,y.map(k=>(0,He.jsxs)("label",{style:h.pickRow,children:[(0,He.jsx)("input",{type:"checkbox",checked:!d.includes(k),onChange:()=>q(k),style:h.pickBox}),(0,He.jsx)("span",{style:h.pickTitle,children:k||e("scriptsUngrouped")})]},k||"__ungrouped"))]}):null,(0,He.jsx)("div",{style:h.quickBarRow,children:l==="empty"?(0,He.jsx)("span",{style:h.hint,children:e("quickScriptsEmpty")}):x.map(k=>(0,He.jsxs)("span",{style:h.quickGroup,children:[(0,He.jsx)("span",{style:h.quickFolder,children:k.folder||e("scriptsUngrouped")}),k.items.map(M=>(0,He.jsx)("button",{type:"button",style:{...h.quickChip,...a===M.name?h.quickChipBusy:null},title:`${M.name}${M.folder?` · ${M.folder}`:""} · ${D(e,"scriptsSteps",{count:M.stepCount})}`,disabled:a!==null,onClick:()=>W(M),children:a===M.name?"…":M.name},M.name))]},k.folder||"__ungrouped"))})]}):(0,He.jsx)("div",{style:h.quickBarCollapsed,children:(0,He.jsx)(Q,{title:e("quickScripts"),ariaLabel:e("quickScripts"),onClick:s,children:e("quickScriptsShow")})})}var $e=require("react");var Y=require("react/jsx-runtime"),Zp=["password","privateKey","agent","none"],$r="__new__";function ph(e){return e==="telnet"?"23":"22"}function Qp(e,t){return e===$r?String(t||"").trim():typeof e=="string"?e:""}function _h({t:e,onCancel:t,onSaved:i,draft:s}){let r=!!(s&&typeof s.id=="string"&&s.id),[n,o]=(0,$e.useState)([]),[l,c]=(0,$e.useState)([]),[a,u]=(0,$e.useState)(!0),[d,_]=(0,$e.useState)(null),[m,p]=(0,$e.useState)(r?s.transport:"ssh"),[g,y]=(0,$e.useState)(r?s.id:""),[x,q]=(0,$e.useState)(r?s.host:""),[W,k]=(0,$e.useState)(String(r?s.port:ph("ssh"))),[M,Z]=(0,$e.useState)(r?s.username:""),[K,ye]=(0,$e.useState)(r?s.authType:"password"),[ce,he]=(0,$e.useState)(""),[G,ke]=(0,$e.useState)(""),[R,E]=(0,$e.useState)(""),[B,A]=(0,$e.useState)(!1),[T,w]=(0,$e.useState)(r?s.name:""),[I,P]=(0,$e.useState)(r&&s.folder?s.folder:""),[re,Re]=(0,$e.useState)(""),[ee,fe]=(0,$e.useState)(!1),[Ge,le]=(0,$e.useState)(null);(0,$e.useEffect)(()=>{let $=!1;return u(!0),Xs().then(pe=>{if($)return;let Ue=Js(pe);o(Ue.profiles),c(Ue.folders.map(Qe=>Qe.name))}).catch(pe=>{$||_(ne(pe))}).finally(()=>{$||u(!1)}),()=>{$=!0}},[]);let O=[...new Set([...l,...r&&s.folder?[s.folder]:[]])],X=r?s:n.find($=>$.id===g),ae=!!X&&(K==="password"&&X.hasPassword||K==="privateKey"&&X.hasPrivateKey),Ke=ae?e("profileUsesSavedSecret"):!!X&&!ae&&(K==="password"||K==="privateKey")?e("profileNeedsSecretHint"):null,ut=$=>{p($),r||y(""),k(pe=>pe==="22"||pe==="23"||pe===""?ph($):pe)},ie=()=>{g&&!r&&y("")},Bt=$=>{if(y($),!$)return;let pe=n.find(Ue=>Ue.id===$);pe&&(p(pe.transport),q(pe.host),k(String(pe.port)),Z(pe.username),ye(pe.authType),P(pe.folder||""),he(""),ke(""),E(""),!T&&pe.name&&w(`${pe.name} copy`))},Et=$=>{if(A($),$&&!T.trim()){let pe=x.trim()?`${M.trim()?`${M.trim()}@`:""}${x.trim()}`:"profile";w(pe)}},ft=()=>{if(!x.trim())return e("errorHostRequired");if(m==="ssh"&&M.trim().length===0)return e("errorUsernameRequired");let $=Number(W);return!Number.isInteger($)||$<1||$>65535?e("errorPort"):null},Ze=$=>ca({id:r?s.id:void 0,order:r?s.order:void 0,name:$,transport:m,host:x,port:Number(W),username:M,authType:K,folder:Qp(I,re),password:ce,privateKey:G,passphrase:R}),Si=async $=>{if($&&typeof $.preventDefault=="function"&&$.preventDefault(),ee)return;let pe=ft();if(pe){le(pe);return}let Ue=T.trim();if(!Ue){le(e("profilesNameRequired"));return}le(null),fe(!0);try{let Qe=await tn(Ze(Ue)),Oe=Qe&&Qe.profile&&Qe.profile.id?Qe.profile.id:s.id;J(e("profilesSaved")),typeof i=="function"?i(Oe):typeof t=="function"&&t()}catch(Qe){le(D(e,"profilesSaveFailed",{message:ne(Qe)}))}finally{fe(!1)}},jt=async $=>{if($&&typeof $.preventDefault=="function"&&$.preventDefault(),ee)return;if(r){await Si();return}let pe=ft();if(pe){le(pe);return}le(null),fe(!0);try{let Ue=x.trim(),Qe=Number(W),Oe={transport:m,host:Ue,port:Qe,cols:100,rows:30};if(g&&(Oe.profileId=g),m==="ssh"){let pt=M.trim();Oe.username=pt,Oe.authType=K,K==="password"&&ce&&(Oe.password=ce),K==="privateKey"&&(G.trim()&&(Oe.privateKey=G),R&&(Oe.passphrase=R))}let Ee=await ge("sessions.create",Oe),De=li(Ee&&Ee.session);if(Ee&&Ee.session&&$t(Ee.session),De&&Ri(De.id),B){let pt=T.trim()||`${M.trim()?`${M.trim()}@`:""}${Ue}`;try{let Rt=await tn(Ze(pt));Rt&&Rt.profile&&Rt.profile.id&&Oa(Rt.profile.id),J(e("profilesSaved"))}catch(Rt){J(D(e,"profileSaveFailed",{message:ne(Rt)}))}}}catch(Ue){le(D(e,"connectFailed",{message:ea(e,Ue)}))}finally{fe(!1)}};return(0,Y.jsxs)("form",{style:h.form,onSubmit:jt,noValidate:!0,children:[(0,Y.jsx)(zo,{title:e(r?"profilesEditTitle":"connectTitle"),hint:r?void 0:e("connectHint"),onBack:typeof t=="function"?t:void 0,backLabel:e("back")}),(0,Y.jsxs)("div",{style:h.formScroll,children:[r?(0,Y.jsx)("span",{style:h.hint,children:e("profilesEditHint")}):null,(0,Y.jsxs)("div",{style:h.row,children:[(0,Y.jsx)("div",{style:h.grow,children:(0,Y.jsx)(Fe,{label:e("transport"),children:(0,Y.jsxs)("select",{style:h.select,value:m,onChange:$=>ut($.target.value),disabled:ee,children:[(0,Y.jsx)("option",{value:"ssh",children:"SSH"}),(0,Y.jsx)("option",{value:"telnet",children:"Telnet"})]})})}),r?null:(0,Y.jsxs)("div",{style:{...h.field,flex:1.4,minWidth:0},children:[(0,Y.jsx)("span",{style:h.label,children:e("profile")}),(0,Y.jsxs)("select",{style:h.select,value:g,onChange:$=>Bt($.target.value),disabled:ee||a,children:[(0,Y.jsx)("option",{value:"",children:e(a?"profileLoading":"profileManual")}),n.map($=>(0,Y.jsx)("option",{value:$.id,children:`${$.name} · ${$.transport} ${$.host}`},$.id))]})]})]}),!a&&n.length===0&&!r?(0,Y.jsx)("span",{style:h.hint,children:e("profileEmpty")}):null,d?(0,Y.jsx)("span",{style:h.hint,children:D(e,"profileLoadFailed",{message:d})}):null,(0,Y.jsxs)("div",{style:h.row,children:[(0,Y.jsx)("div",{style:h.grow,children:(0,Y.jsx)(Fe,{label:e("host"),children:(0,Y.jsx)("input",{style:h.input,value:x,onChange:$=>{ie(),q($.target.value)},placeholder:"10.0.0.5",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:ee})})}),(0,Y.jsx)("div",{style:h.portField,children:(0,Y.jsx)(Fe,{label:e("port"),children:(0,Y.jsx)("input",{style:h.input,value:W,onChange:$=>{ie(),k($.target.value.replace(/[^0-9]/g,""))},inputMode:"numeric",disabled:ee})})})]}),m==="ssh"?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Fe,{label:e("username"),children:(0,Y.jsx)("input",{style:h.input,value:M,onChange:$=>{ie(),Z($.target.value)},placeholder:"root",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,disabled:ee})}),(0,Y.jsx)(Fe,{label:e("authType"),children:(0,Y.jsx)("select",{style:h.select,value:K,onChange:$=>{ie(),ye($.target.value)},disabled:ee,children:Zp.map($=>(0,Y.jsx)("option",{value:$,children:e(`auth${$.charAt(0).toUpperCase()}${$.slice(1)}`)},$))})}),K==="password"?(0,Y.jsx)(Fe,{label:e("password"),hint:Ke||e("passwordHint"),children:(0,Y.jsx)("input",{style:h.input,type:"password",value:ce,onChange:$=>he($.target.value),autoComplete:"new-password",disabled:ee})}):null,K==="privateKey"?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Fe,{label:e("privateKey"),hint:Ke||e("privateKeyHint"),children:(0,Y.jsx)("textarea",{style:h.textarea,value:G,onChange:$=>ke($.target.value),spellCheck:!1,autoComplete:"off",disabled:ee})}),(0,Y.jsx)(Fe,{label:e("passphrase"),children:(0,Y.jsx)("input",{style:h.input,type:"password",value:R,onChange:$=>E($.target.value),autoComplete:"new-password",disabled:ee})})]}):null]}):(0,Y.jsx)("span",{style:h.hint,children:e("passwordHint")}),(0,Y.jsx)(Fe,{label:e("folder"),hint:I===$r?e("folderName"):void 0,children:(0,Y.jsxs)("select",{style:h.select,value:I,"aria-label":e("folder"),onChange:$=>P($.target.value),disabled:ee,children:[(0,Y.jsx)("option",{value:"",children:e("folderNone")}),O.map($=>(0,Y.jsx)("option",{value:$,children:$},$)),(0,Y.jsx)("option",{value:$r,children:e("folderNew")})]})}),I===$r?(0,Y.jsx)(Fe,{label:e("folderName"),children:(0,Y.jsx)("input",{style:h.input,value:re,"aria-label":e("folderName"),placeholder:e("folderName"),autoComplete:"off",spellCheck:!1,onChange:$=>Re($.target.value),disabled:ee})}):null,r?(0,Y.jsx)(Fe,{label:e("profileName"),children:(0,Y.jsx)("input",{style:h.input,value:T,"aria-label":e("profileName"),onChange:$=>w($.target.value),disabled:ee})}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)("label",{style:h.checkboxRow,children:[(0,Y.jsx)("input",{type:"checkbox",style:h.checkbox,checked:B,onChange:$=>Et($.target.checked),disabled:ee}),e("saveProfile")]}),B?(0,Y.jsx)(Fe,{label:e("profileName"),children:(0,Y.jsx)("input",{style:h.input,value:T,"aria-label":e("profileName"),onChange:$=>w($.target.value),disabled:ee})}):null]}),Ge?(0,Y.jsx)("div",{style:h.formError,role:"alert",children:Ge}):null]}),(0,Y.jsxs)("div",{style:h.formActions,children:[typeof t=="function"?(0,Y.jsx)(Q,{onClick:t,disabled:ee,children:e("cancel")}):null,(0,Y.jsx)(Q,{type:"submit",variant:"primary",onClick:jt,busy:ee,disabled:ee,children:e(r?ee?"connectingAction":"profilesSaveAction":ee?"connectingAction":"connectAction")})]})]})}var yi=require("react");var xt=require("react/jsx-runtime"),e_={read:"auditRead",write:"auditWrite",deny:"auditDeny",lock:"auditLock"};function t_(e){try{return new Date(e).toLocaleTimeString(void 0,{hour12:!1})}catch{return""}}function i_(e){return String(e||"").replace(/\s+/g," ").trim()}function mh({t:e,sessionId:t,open:i,onClose:s,rootRef:r}){let n=zt(),o=(0,yi.useRef)(null),[l,c]=(0,yi.useState)(!1),[a,u]=(0,yi.useState)(null);if((0,yi.useEffect)(()=>{if(!i||!t)return;let _=!1;return c(!0),u(null),ge("audit.list",{id:t,limit:100}).then(m=>{if(_)return;let p=m&&Array.isArray(m.entries)?m.entries:[];Fa(t,p)}).catch(m=>{_||u(ne(m))}).finally(()=>{_||c(!1)}),()=>{_=!0}},[i,t]),(0,yi.useEffect)(()=>{if(!i)return;let _=p=>{let g=r&&r.current;g&&p.target instanceof Node&&g.contains(p.target)||s()},m=p=>{p.key==="Escape"&&(p.stopPropagation(),typeof p.preventDefault=="function"&&p.preventDefault(),s())};return document.addEventListener("mousedown",_,!0),document.addEventListener("keydown",m,!0),()=>{document.removeEventListener("mousedown",_,!0),document.removeEventListener("keydown",m,!0)}},[i,s,r]),!i||!t)return null;let d=(n.audit[t]||[]).slice().reverse();return(0,xt.jsxs)("div",{ref:o,style:h.popover,role:"dialog","aria-label":e("audit"),children:[(0,xt.jsx)("div",{style:h.popoverHeader,children:(0,xt.jsx)("span",{style:{flex:1,minWidth:0},children:e("audit")})}),(0,xt.jsxs)("div",{style:h.auditList,children:[l&&d.length===0?(0,xt.jsx)("div",{style:h.auditEmpty,children:e("auditLoading")}):null,!l&&d.length===0?(0,xt.jsx)("div",{style:h.auditEmpty,children:e("auditEmpty")}):null,d.map((_,m)=>{let p=e_[_.action]||"auditRead",g=_.source==="ai"?e("sourceAi"):e("sourceHuman"),y=i_(_.detail);return(0,xt.jsxs)("div",{style:h.auditRow,title:y||void 0,children:[(0,xt.jsx)("span",{style:h.auditTime,children:t_(_.at)}),(0,xt.jsx)("span",{style:{...h.auditBadge,color:_.source==="ai"?f.warnLabel:f.labelSecondary},children:g}),(0,xt.jsx)("span",{style:{...h.auditBadge,color:_.action==="deny"?f.danger:f.labelSecondary},children:e(p)}),(0,xt.jsx)("span",{style:h.auditDetail,children:y||"—"})]},`${_.at}-${m}`)})]}),a?(0,xt.jsx)("div",{style:{...h.formError,margin:6},children:D(e,"auditFailed",{message:a})}):null]})}var ue=require("react");var F=require("react/jsx-runtime"),s_=["0","1","2","3","4","5"];function gh({line:e}){return(0,F.jsxs)("div",{style:h.matchRow,children:[(0,F.jsx)("span",{style:h.matchTime}),(0,F.jsx)("span",{style:h.contextText,children:e})]})}function r_({match:e,pattern:t}){let i=xa(e.line,t);return(0,F.jsxs)("div",{style:h.matchRow,children:[(0,F.jsx)("span",{style:h.matchTime,children:ln(e.at)}),(0,F.jsx)("span",{style:h.matchText,children:i.map((s,r)=>s.hit?(0,F.jsx)("span",{style:h.matchHit,children:s.text},`h${r}`):(0,F.jsx)("span",{children:s.text},`p${r}`))})]})}function vh({t:e,sessionId:t,onClose:i}){let[s,r]=(0,ue.useState)([]),[n,o]=(0,ue.useState)("loading"),[l,c]=(0,ue.useState)(null),[a,u]=(0,ue.useState)(!1),[d,_]=(0,ue.useState)(0),[m,p]=(0,ue.useState)(""),[g,y]=(0,ue.useState)(0),[x,q]=(0,ue.useState)(!1),W=(0,ue.useRef)(0),k=(0,ue.useRef)(!1),[M,Z]=(0,ue.useState)(!1),[K,ye]=(0,ue.useState)(null),[ce,he]=(0,ue.useState)(null),[G,ke]=(0,ue.useState)(!1),[R,E]=(0,ue.useState)(!1),[B,A]=(0,ue.useState)(""),[T,w]=(0,ue.useState)(""),[I,P]=(0,ue.useState)(""),[re,Re]=(0,ue.useState)("0"),[ee,fe]=(0,ue.useState)(null),[Ge,le]=(0,ue.useState)(null),[O,X]=(0,ue.useState)({enabled:!1,dir:"",needsReview:!1}),[ae,kt]=(0,ue.useState)(!1),[Ke,ut]=(0,ue.useState)(!0),[ie,Bt]=(0,ue.useState)(null),[Et,ft]=(0,ue.useState)(!0),[Ze,Si]=(0,ue.useState)(null),[jt,$]=(0,ue.useState)(""),[pe,Ue]=(0,ue.useState)(null),[Qe,Oe]=(0,ue.useState)("idle"),[Ee,De]=(0,ue.useState)(null),[pt,Rt]=(0,ue.useState)(null),oi=(0,ue.useRef)(null),Ce=(0,ue.useRef)(0),qe=(0,ue.useRef)(!0);(0,ue.useEffect)(()=>{k.current=G},[G]),(0,ue.useEffect)(()=>{qe.current=!0;let S=!1,V=++W.current;return(async()=>{!S&&V===W.current&&(o("loading"),c(null));try{let _e=await Zs({limit:50});if(S||!qe.current||V!==W.current)return;let Le=_e&&Array.isArray(_e.sessions)?_e.sessions.map(ki).filter(Boolean):[];r(Le),o(Le.length>0?"ready":"empty"),u(_e?.truncated===!0),_(typeof _e?.total=="number"?_e.total:Le.length),p(typeof _e?.snapshot=="string"?_e.snapshot:""),y(Le.length),q(_e?.limitReached===!0);let mt=Le.find(Ht=>Ht.id===t)||Le[0];ye(mt?mt.id:null),he(mt&&mt.historyId||null)}catch(_e){if(S||!qe.current||V!==W.current)return;c(ne(_e)),o("error")}})(),()=>{S=!0,qe.current=!1,W.current+=1}},[]);async function Mt(S=K,V=ce,j={since:B,until:T,search:I,context:re}){if(!S){Oe("empty"),De(null),fe(null);return}let _e=an(j.since),Le=an(j.until);if(!_e.ok){Oe("error"),De(D(e,"historyTimeInvalid",{value:String(j.since||"").trim()}));return}if(!Le.ok){Oe("error"),De(D(e,"historyTimeInvalid",{value:String(j.until||"").trim()}));return}let mt=Ce.current+1;Ce.current=mt,Oe("loading"),De(null),le(wa(j.search));try{let Ht={sessionId:S,since:_e.at,until:Le.at,search:Ca(j.search),context:Number(j.context)||0,maxMatches:200},Hi=G?await ua(Ht):await _a({...Ht,historyId:V||void 0});if(Ce.current!==mt||!qe.current)return;let _t=ga(Hi);fe(_t);let Wi=_t.matches.length===0?_t.text.trim():"";Oe(_t.matches.length>0||Wi!==""?"ready":"empty")}catch(Ht){if(Ce.current!==mt||!qe.current)return;De(D(e,"historyQueryFailed",{message:ne(Ht)})),Oe("error"),fe(null)}}(0,ue.useEffect)(()=>{K&&Mt(K,ce,{since:B,until:T,search:I,context:re})},[K,ce,G]);let is=S=>{let V=S&&typeof S=="object"&&S.id?S.id:S,j=S&&typeof S=="object"&&typeof S.historyId=="string"?S.historyId:null;if(V===K&&j===ce){Mt(V,j);return}ye(V),he(j),fe(null),Oe("idle"),De(null),Rt(null)},bi=ee&&ee.matches.length===0&&ee.text.trim()!==""?ee.text.replace(/\n+$/,"").split(`
|
|
386
|
+
`):[],wi=!!(ee&&ee.matches.length>0),Ci=wi||bi.length>0,zs=wi?ee.matches.length:bi.length,ss=async()=>{if(!Ci)return;let S=wi?ee.matches.map(V=>`${ln(V.at)} ${V.line}`).join(`
|
|
387
|
+
`):ee.text;try{await rr(S,oi.current)?J(e("copied")):(Rt(S),J(e("historyCopyFailed")))}catch{Rt(S),J(e("historyCopyFailed"))}};(0,ue.useEffect)(()=>{let S=!1;return pa().then(V=>{S||!V||(X({enabled:V.enabled===!0,dir:typeof V.dir=="string"?V.dir:"",needsReview:V.needsReview===!0}),ut(!1))}).catch(V=>{S||(ut(!1),V&&V.code==="UNKNOWN_METHOD"?ft(!1):Bt(ne(V)))}),()=>{S=!0}},[]);let $s=async S=>{if(!jt){$(S),Ue(null);try{let V=S==="all"?{all:!0}:{sessionId:K||t||void 0,historyId:ce||void 0},j=G&&S!=="all"?await fa({sessionId:V.sessionId}):await da(V);Si(j||null);let _e=j&&Array.isArray(j.files)?j.files:[],Le=j&&Array.isArray(j.skipped)?j.skipped:[],mt=j&&Number.isInteger(j.skippedTotal)?j.skippedTotal:Le.length;J(_e.length>0?D(e,"historyExportDone",{count:_e.length}):mt>0?D(e,"historyExportSkippedTitle",{count:mt}):e("historyExportEmpty"))}catch(V){V&&V.code==="UNKNOWN_METHOD"?(ft(!1),Ue(e("historyExportNeedsRestart"))):Ue(ne(V))}finally{$("")}}},Ks=async S=>{if(!(ae||Ke||ie!==null)&&!(O.needsReview&&S!==!1)){kt(!0);try{let V=typeof S=="boolean"?S:!O.enabled,j=await on({enabled:V});X({enabled:j&&j.enabled===!0,dir:j&&typeof j.dir=="string"?j.dir:O.dir,needsReview:j&&typeof j.needsReview=="boolean"?j.needsReview:!1}),J(j&&j.enabled===!0?e("historyAutoLogOn"):e("historyAutoLogOff"))}catch(V){V&&V.code==="UNKNOWN_METHOD"?(ft(!1),J(e("historyExportNeedsRestart"))):J(D(e,"historyAutoLogFailed",{message:ne(V)}))}finally{kt(!1)}}},ai=async()=>{if(!(ae||Ke||ie!==null)){kt(!0);try{let S=await on({enabled:!0,dir:O.dir,confirmLegacy:!0});X({enabled:S&&S.enabled===!0,dir:S&&typeof S.dir=="string"?S.dir:O.dir,needsReview:!1}),J(S&&S.enabled===!0?e("historyAutoLogOn"):e("historyAutoLogOffHint"))}catch(S){S&&S.code==="UNKNOWN_METHOD"?(ft(!1),J(e("historyExportNeedsRestart"))):J(D(e,"historyAutoLogFailed",{message:ne(S)}))}finally{kt(!1)}}},xi=async()=>{let S=++W.current;Ce.current+=1,fe(null),Oe("idle"),De(null),Rt(null),le(null),Z(!1),r([]),u(!1),q(!1),_(0),p(""),y(0),o("loading"),c(null);try{let V=await Zs({limit:50});if(!qe.current||S!==W.current)return;let j=V&&Array.isArray(V.sessions)?V.sessions.map(ki).filter(Boolean):[];r(j),o(j.length>0?"ready":"empty"),u(V?.truncated===!0),_(typeof V?.total=="number"?V.total:j.length),p(typeof V?.snapshot=="string"?V.snapshot:""),y(j.length),q(V?.limitReached===!0);let _e=j.find(Le=>Le.id===t)||j[0];ye(_e?_e.id:null),he(_e&&_e.historyId||null),fe(null),Oe("idle"),De(null),Rt(null)}catch(V){if(!qe.current||S!==W.current)return;c(ne(V)),o("error")}},Us=async(S=!1)=>{if(R&&S!==!0)return;let V=++W.current;Z(!1),E(!0),Ce.current+=1,ke(!0),r([]),u(!1),q(!1),_(0),p(""),y(0),ye(null),he(null),o("loading"),c(null),fe(null),Oe("idle"),De(null),Si(null),Ue(null);try{let j=await nn({limit:50});if(!qe.current||V!==W.current)return;let _e=j&&Array.isArray(j.sessions)?j.sessions.map(ki).filter(Boolean):[];r(_e),o(_e.length>0?"ready":"empty"),u(j?.truncated===!0),_(typeof j?.total=="number"?j.total:_e.length),p(typeof j?.snapshot=="string"?j.snapshot:""),y(_e.length),q(j?.limitReached===!0),ye(_e[0]?_e[0].id:null),he(null)}catch(j){if(!qe.current||V!==W.current)return;c(ne(j)),o("error")}finally{qe.current&&V===W.current&&E(!1)}},Yr=async()=>{if(!R){W.current+=1,Z(!1),E(!0),Ce.current+=1,ke(!1),r([]),u(!1),q(!1),_(0),p(""),y(0),ye(null),he(null),Si(null),Ue(null);try{await xi()}finally{E(!1)}}},qs=async()=>{if(M||x)return;let S=++W.current,V=G,j=m,_e=g;Z(!0);try{let Le=V?await nn({limit:50,offset:_e,snapshot:j}):await Zs({limit:50,offset:_e,snapshot:j});if(!qe.current||S!==W.current||V!==k.current)return;if(Le?.stale===!0){J(e("historyStaleReload")),V?await Us(!0):await xi();return}let mt=Le&&Array.isArray(Le.sessions)?Le.sessions.map(ki).filter(Boolean):[],Ht=new Set(s.map(_t=>_t.historyId||`${_t.id}:${_t.createdAt}`)),Hi=mt.filter(_t=>{let Wi=_t.historyId||`${_t.id}:${_t.createdAt}`;return Ht.has(Wi)?!1:(Ht.add(Wi),!0)});r([...s,...Hi]),u(Le?.truncated===!0),_(typeof Le?.total=="number"?Le.total:d),p(typeof Le?.snapshot=="string"?Le.snapshot:j),y(_e+mt.length),q(Le?.limitReached===!0)}catch(Le){if(!qe.current||S!==W.current||V!==k.current)return;J(D(e,"historySessionsFailed",{message:ne(Le)}))}finally{qe.current&&S===W.current&&Z(!1)}},Gr=(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:ee?`${D(e,"historyFooter",{size:Ei(ee.scannedBytes),count:zs})}${ee.truncated?` · ${e("historyTruncated")}`:""}`:e("historyEmptyQuery")}),(0,F.jsx)("span",{style:h.controlSpacer}),(0,F.jsx)(Q,{onClick:ss,disabled:!Ci,title:e("historyCopy"),children:e("historyCopy")}),(0,F.jsx)(Q,{onClick:()=>$s("current"),busy:jt==="current",disabled:jt!==""||!Et,title:Et?D(e,"historyExportHint",{dir:O.dir||"~/.dsh/aiterm/exports"}):e("historyExportNeedsRestart"),children:e("historyExportOne")}),(0,F.jsx)(Q,{onClick:()=>$s("all"),busy:jt==="all",disabled:jt!==""||!Et||G,title:e(G?"historyLegacyHint":Et?"historyExportAllHint":"historyExportNeedsRestart"),children:e("historyExportAll")})]});return(0,F.jsxs)(Fi,{title:e("historyTitle"),onBack:i,backLabel:e("historyPanelClose"),footer:Gr,children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,F.jsx)("div",{style:h.sectionTitle,children:e("historySessionsTitle")}),(0,F.jsx)("span",{style:h.controlSpacer}),(0,F.jsx)(Q,{onClick:G?Yr:Us,busy:R,title:e("historyLegacyHint"),children:e(G?"historyLegacyBack":"historyLegacyEntry")})]}),G?(0,F.jsx)("div",{style:h.hint,children:e("historyLegacyHint")}):null,G&&n==="loading"?(0,F.jsx)("div",{style:h.auditEmpty,children:e("historyLegacyLoading")}):null,n==="loading"&&!G?(0,F.jsx)("div",{style:h.auditEmpty,children:e("historyLoadingSessions")}):null,n==="error"?(0,F.jsx)("div",{style:h.formError,role:"alert",children:D(e,"historySessionsFailed",{message:l})}):null,n==="empty"?(0,F.jsx)("div",{style:h.auditEmpty,children:e("historySessionsEmpty")}):null,a?(0,F.jsxs)("div",{style:h.actionRow,children:[(0,F.jsx)("span",{style:h.hint,role:"status",children:x?D(e,"historySessionsLimitReached",{shown:s.length,total:d}):D(e,"historySessionsTruncated",{shown:s.length,total:d})}),x?null:(0,F.jsx)(Q,{onClick:qs,busy:M,disabled:M||R,children:e("historyLoadMore")})]}):null,s.length>0?(0,F.jsx)("div",{style:h.listBox,role:"listbox","aria-label":e("historySessionsTitle"),children:s.map(S=>{let V=S.id===K&&(S.historyId||null)===ce,j=S.createdAt>0?cn(S.createdAt):"—",_e=S.closedAt?cn(S.closedAt):e("historyOngoing");return(0,F.jsxs)("button",{type:"button",role:"option","aria-selected":V,title:`${S.title} · ${S.host||S.transport}`,style:{...h.listRow,...V?h.listRowActive:null},onClick:()=>is(S),children:[(0,F.jsx)("span",{style:h.listRowTitle,children:S.title}),(0,F.jsx)("span",{style:h.listRowMeta,children:`${S.host||S.transport} · ${j}→${_e} · ${Ei(S.bytes)}`})]},S.historyId?`h:${S.historyId}`:`l:${S.id}:${S.createdAt}`)})}):null,(0,F.jsxs)("div",{style:h.filterRow,children:[(0,F.jsx)(Fe,{label:e("historySince"),style:h.grow,children:(0,F.jsx)("input",{style:h.input,value:B,placeholder:"10m",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:S=>A(S.target.value),onKeyDown:S=>{S&&S.key==="Enter"&&Mt()}})}),(0,F.jsx)(Fe,{label:e("historyUntil"),style:h.grow,children:(0,F.jsx)("input",{style:h.input,value:T,placeholder:"",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:S=>w(S.target.value),onKeyDown:S=>{S&&S.key==="Enter"&&Mt()}})}),(0,F.jsx)("div",{style:{flex:"none",width:62},children:(0,F.jsx)(Fe,{label:e("historyContext"),children:(0,F.jsx)("select",{style:h.select,value:re,onChange:S=>Re(S.target.value),children:s_.map(S=>(0,F.jsx)("option",{value:S,children:S},S))})})})]}),(0,F.jsx)(Fe,{label:e("historySearch"),hint:e("historySearchHint"),children:(0,F.jsx)("input",{style:h.input,value:I,placeholder:"error|timeout",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,onChange:S=>P(S.target.value),onKeyDown:S=>{S&&S.key==="Enter"&&Mt()}})}),(0,F.jsx)("div",{style:h.actionRow,children:(0,F.jsx)(Q,{variant:"primary",onClick:()=>Mt(),disabled:!K||Qe==="loading",children:e(Qe==="loading"?"historyQuerying":"historyQuery")})}),Qe==="error"&&Ee?(0,F.jsx)("div",{style:h.formError,role:"alert",children:Ee}):null,!K&&n!=="loading"?(0,F.jsx)("div",{style:h.auditEmpty,children:e("historyNeedSession")}):null,Qe==="empty"&&!Ee?(0,F.jsxs)("div",{style:h.auditEmpty,children:[e("historyNoMatches"),(0,F.jsx)("span",{style:{display:"block",fontSize:10},children:e("historyNoMatchesHint")})]}):null,wi?(0,F.jsx)("div",{ref:oi,style:h.scrollArea,children:ee.matches.map((S,V)=>(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:"none",padding:"2px 0",borderBottom:`0.5px solid ${f.borderL1}`},children:[S.before.map((j,_e)=>(0,F.jsx)(gh,{line:j},`b${_e}`)),(0,F.jsx)(r_,{match:S,pattern:Ge}),S.after.map((j,_e)=>(0,F.jsx)(gh,{line:j},`a${_e}`))]},`${S.at}-${V}`))}):null,!wi&&bi.length>0?(0,F.jsxs)("div",{ref:oi,style:h.scrollArea,children:[(0,F.jsx)("div",{style:h.hint,children:e("historyFragment")}),bi.map((S,V)=>(0,F.jsx)("div",{style:h.matchRow,children:(0,F.jsx)("span",{style:h.matchText,children:S})},`f${V}`))]}):null,(0,F.jsx)("div",{style:h.sectionTitle,children:e("historyLogFileTitle")}),Et?null:(0,F.jsx)("div",{style:h.hint,role:"status",children:e("historyExportNeedsRestart")}),(0,F.jsxs)("label",{style:h.checkRow,children:[(0,F.jsx)("input",{type:"checkbox",checked:O.enabled,disabled:ae||Ke||ie!==null||!Et||O.needsReview,onChange:()=>Ks(),style:h.pickBox}),(0,F.jsx)("span",{style:h.checkLabel,children:e("historyAutoLogLabel")})]}),(0,F.jsx)("span",{style:h.hint,children:O.enabled?D(e,"historyAutoLogWhere",{dir:O.dir}):e("historyAutoLogOffHint")}),Ke?(0,F.jsx)("div",{style:h.hint,role:"status",children:e("historyAutoLogLoading")}):null,ie!==null?(0,F.jsx)("div",{style:h.formError,role:"alert",children:D(e,"historyAutoLogLoadFailed",{message:ie})}):null,O.needsReview?(0,F.jsx)("div",{style:h.hint,role:"status",children:e("historyAutoLogLegacyReview")}):null,O.needsReview?(0,F.jsx)("div",{style:h.hint,role:"status",children:D(e,"historyAutoLogLegacyPath",{dir:O.dir})}):null,O.needsReview?(0,F.jsxs)("div",{style:h.actionRow,children:[(0,F.jsx)(Q,{onClick:()=>Ks(!1),disabled:ae||Ke||ie!==null||!Et,children:e("historyAutoLogLegacyKeepOff")}),(0,F.jsx)(Q,{onClick:ai,disabled:ae||Ke||ie!==null||!Et,children:e("historyAutoLogLegacyEnable")})]}):null,pe?(0,F.jsx)("div",{style:h.formError,role:"alert",children:D(e,"historyExportFailed",{message:pe})}):null,Ze?(0,F.jsxs)("div",{style:h.exportBox,role:"status",children:[(0,F.jsx)("div",{style:h.hint,children:D(e,"historyExportWhere",{dir:Ze.dir||""})}),(Number.isInteger(Ze.skippedTotal)?Ze.skippedTotal:(Ze.skipped||[]).length)>0?(0,F.jsx)("div",{style:h.hint,children:D(e,"historyExportSkipped",{count:Number.isInteger(Ze.skippedTotal)?Ze.skippedTotal:(Ze.skipped||[]).length,sessions:(Ze.skipped||[]).map(S=>S.sessionId).join(", ")})}):null,Ze.omitted?(0,F.jsx)("div",{style:h.hint,children:D(e,"historyExportOmitted",{count:Ze.omitted.count,reason:Ze.omitted.reason,limit:Ze.omitted.limit})}):null,(Ze.files||[]).map(S=>(0,F.jsxs)("div",{style:h.exportRow,children:[(0,F.jsx)("span",{style:h.exportPath,title:S.path,children:S.path}),(0,F.jsx)("span",{style:h.exportMeta,children:`${Ei(S.bytes)} · ${D(e,"historyExportLines",{count:S.lines})}`})]},S.path))]}):null,pt!==null?(0,F.jsxs)("div",{style:{flex:"none",padding:6,border:`0.5px solid ${f.borderL2}`,borderRadius:f.radiusSm,background:f.bgLayer1},children:[(0,F.jsx)("div",{style:h.hint,children:e("historyManualCopy")}),(0,F.jsx)("textarea",{style:h.textarea,readOnly:!0,value:pt,onFocus:S=>{try{S.target.select()}catch{}}})]}):null]})}var rt=require("react");var te=require("react/jsx-runtime"),Kr="__new__";function yh(e){let t=e.username?`${e.username}@`:"";return`${e.transport} ${t}${e.host}:${e.port}`}function n_({profile:e,t,busy:i,renaming:s,moving:r,confirmed:n,highlighted:o,folderOptions:l,rowRef:c,handlers:a}){let u=!!(s&&s.id===e.id),d=!!(r&&r.id===e.id),_=[];return e.hasPassword&&_.push({key:"password",label:t("profilesBadgePassword")}),e.hasPrivateKey&&_.push({key:"privateKey",label:t("profilesBadgePrivateKey")}),e.hasPassphrase&&_.push({key:"passphrase",label:t("profilesBadgePassphrase")}),(0,te.jsxs)("div",{ref:c,"data-profile-id":e.id,style:{...h.profileRow,...o?h.profileRowHighlight:null},children:[(0,te.jsxs)("div",{style:h.profileMain,children:[(0,te.jsx)("span",{style:h.profileName,title:e.name,children:e.name}),(0,te.jsx)("span",{style:h.profileAddress,title:yh(e),children:yh(e)}),_.length>0?(0,te.jsx)("span",{style:h.profileBadges,children:_.map(m=>(0,te.jsx)("span",{style:h.badge,children:m.label},m.key))}):null]}),u?(0,te.jsxs)("div",{style:h.inlineRow,children:[(0,te.jsx)("input",{style:{...h.input,width:140},value:s.value,"aria-label":t("profilesNamePlaceholder"),autoComplete:"off",spellCheck:!1,disabled:i,onChange:m=>a.onRenameInput(m.target.value),onKeyDown:m=>{m&&(m.key==="Enter"&&a.onRenameSubmit(e),m.key==="Escape"&&(m.stopPropagation(),a.onRenameCancel()))}}),(0,te.jsx)(Q,{variant:"primary",title:`${t("profilesRenameSave")} ${e.name}`,disabled:i,onClick:()=>a.onRenameSubmit(e),children:t("profilesRenameSave")}),(0,te.jsx)(Q,{title:`${t("profilesRenameCancel")} ${e.name}`,disabled:i,onClick:a.onRenameCancel,children:t("profilesRenameCancel")})]}):null,d?(0,te.jsxs)("div",{style:h.inlineRow,children:[(0,te.jsxs)("select",{style:{...h.select,width:120},value:r.value,"aria-label":`${t("profilesMove")} ${e.name}`,disabled:i,onChange:m=>a.onMoveInput(m.target.value),children:[(0,te.jsx)("option",{value:"",children:t("folderNone")}),l.map(m=>(0,te.jsx)("option",{value:m,children:m},m)),(0,te.jsx)("option",{value:Kr,children:t("folderNew")})]}),r.value===Kr?(0,te.jsx)("input",{style:{...h.input,width:110},value:r.folder,"aria-label":`${t("folderName")} ${e.name}`,placeholder:t("folderName"),autoComplete:"off",spellCheck:!1,disabled:i,onChange:m=>a.onMoveFolderInput(m.target.value),onKeyDown:m=>{m&&(m.key==="Enter"&&a.onMoveSubmit(e),m.key==="Escape"&&(m.stopPropagation(),a.onMoveCancel()))}}):null,(0,te.jsx)(Q,{variant:"primary",title:`${t("profilesRenameSave")} ${e.name}`,disabled:i,onClick:()=>a.onMoveSubmit(e),children:t("profilesRenameSave")}),(0,te.jsx)(Q,{title:`${t("profilesRenameCancel")} ${e.name}`,disabled:i,onClick:a.onMoveCancel,children:t("profilesRenameCancel")})]}):null,u||d?null:n?(0,te.jsx)(vi,{message:D(t,"profilesDeletePrompt",{name:e.name}),confirmLabel:t("profilesDeleteConfirm"),cancelLabel:t("cancel"),busy:i,onConfirm:()=>a.onDeleteConfirm(e),onCancel:a.onDeleteCancel}):(0,te.jsxs)("div",{style:h.profileActions,children:[(0,te.jsx)(Q,{variant:"primary",style:h.rowBtn,title:`${t("profilesConnect")} ${e.name}`,disabled:i,onClick:()=>a.onConnect(e),children:t("profilesConnect")}),(0,te.jsx)(Q,{style:h.rowBtn,title:`${t("profilesEdit")} ${e.name}`,disabled:i,onClick:()=>a.onEdit(e),children:t("profilesEdit")}),(0,te.jsx)(Q,{style:h.rowBtn,title:`${t("profilesRename")} ${e.name}`,disabled:i,onClick:()=>a.onRenameStart(e),children:t("profilesRename")}),(0,te.jsx)(Q,{style:h.rowBtn,title:`${t("profilesMove")} ${e.name}`,disabled:i,onClick:()=>a.onMoveStart(e),children:t("profilesMove")}),(0,te.jsx)(Q,{style:h.rowBtn,variant:"danger",title:`${t("profilesDelete")} ${e.name}`,disabled:i,onClick:()=>a.onDeleteStart(e),children:t("profilesDelete")})]})]})}function Sh({t:e,onClose:t}){let s=zt().highlightProfileId||null,[r,n]=(0,rt.useState)([]),[o,l]=(0,rt.useState)([]),[c,a]=(0,rt.useState)("loading"),[u,d]=(0,rt.useState)(null),[_,m]=(0,rt.useState)(null),[p,g]=(0,rt.useState)(!1),[y,x]=(0,rt.useState)(null),[q,W]=(0,rt.useState)(null),[k,M]=(0,rt.useState)(null),[Z,K]=(0,rt.useState)(""),[ye,ce]=(0,rt.useState)([]),he=(0,rt.useRef)(!0),G=(0,rt.useRef)(null),ke=(0,rt.useRef)(new Map);async function R(){a("loading"),d(null);try{let O=await Xs();if(!he.current)return;let X=Js(O);n(X.profiles),l(X.folders.map(ae=>ae.name)),a(X.profiles.length>0?"ready":"empty")}catch(O){if(!he.current)return;d(ne(O)),a("error")}}(0,rt.useEffect)(()=>(he.current=!0,R(),()=>{he.current=!1}),[]),(0,rt.useEffect)(()=>{if(!s)return;let O=ke.current.get(s);if(O&&typeof O.scrollIntoView=="function")try{O.scrollIntoView({block:"nearest"})}catch{}},[s,r.length]);let E=[...new Set([...o,...ye,...r.map(O=>O.folder).filter(Boolean)])].sort((O,X)=>O.localeCompare(X)),B=la(r);async function A(O){if(!p){g(!0),m(null);try{await O()}catch(X){let ae=ne(X);he.current&&(m(ae),J(D(e,"profilesActionFailed",{message:ae})))}finally{he.current&&g(!1)}}}let T=O=>A(async()=>{let X=await ge("sessions.create",{profileId:O.id,transport:O.transport,host:O.host,port:O.port,username:O.username,cols:100,rows:30}),ae=li(X&&X.session);X&&X.session&&$t(X.session),ae&&Ri(ae.id)}),w=O=>Vi(O),I=O=>{x(null),W(null),m(null),M(O.id)},P=()=>M(null),re=O=>{M(null),A(async()=>{await aa(O.id),J(e("profilesDeleteDone")),await R()})},Re=O=>{let X=y&&y.id===O.id?String(y.value||"").trim():"";if(X===""){m(e("profilesNameRequired"));return}x(null),A(async()=>{await na(O.id,X),J(e("profilesRenamed")),await R()})},ee=O=>{if(!q||q.id!==O.id)return;let X=q.value===Kr?String(q.folder||"").trim():q.value;if(q.value===Kr&&X===""){m(e("profilesFolderNameRequired"));return}W(null),A(async()=>{await oa(O.id,X),J(e("profilesMoved")),await R()})},fe=()=>{let O=Z.trim();if(O===""){m(e("profilesFolderNameRequired"));return}m(null),ce(X=>X.includes(O)?X:X.concat([O])),K(""),J(D(e,"profilesFolderAdded",{name:O}))},Ge={onConnect:T,onEdit:w,onRenameStart:O=>{W(null),M(null),m(null),x({id:O.id,value:O.name})},onRenameInput:O=>x(X=>X&&{...X,value:O}),onRenameSubmit:Re,onRenameCancel:()=>x(null),onMoveStart:O=>{x(null),M(null),m(null),W({id:O.id,value:O.folder||"",folder:""})},onMoveInput:O=>W(X=>X&&{...X,value:O}),onMoveFolderInput:O=>W(X=>X&&{...X,folder:O}),onMoveSubmit:ee,onMoveCancel:()=>W(null),onDeleteStart:I,onDeleteConfirm:re,onDeleteCancel:P},le=(0,te.jsxs)(te.Fragment,{children:[(0,te.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:D(e,"profilesFooter",{profiles:r.length,folders:E.length})}),(0,te.jsx)("span",{style:h.controlSpacer}),(0,te.jsx)(Q,{onClick:R,disabled:p||c==="loading",children:e("profilesReload")})]});return(0,te.jsxs)(Fi,{title:e("profilesTitle"),onBack:typeof t=="function"?t:void 0,backLabel:e("profilesPanelClose"),actions:(0,te.jsx)(Q,{variant:"primary",onClick:()=>Vi(),disabled:p,children:e("profilesNewConnection")}),footer:le,children:[(0,te.jsxs)("div",{style:h.folderPickerRow,children:[(0,te.jsx)(Fe,{label:e("profilesNewFolder"),style:h.grow,children:(0,te.jsx)("input",{style:h.input,value:Z,placeholder:e("profilesNewFolderPlaceholder"),"aria-label":e("profilesNewFolderPlaceholder"),autoComplete:"off",spellCheck:!1,disabled:p,onChange:O=>K(O.target.value),onKeyDown:O=>{O&&O.key==="Enter"&&fe()}})}),(0,te.jsx)(Q,{onClick:fe,disabled:p||Z.trim()==="",title:e("profilesCreateFolder"),children:e("profilesCreateFolder")})]}),_?(0,te.jsx)("div",{style:h.formError,role:"alert",children:_}):null,c==="loading"&&r.length===0?(0,te.jsx)("div",{style:h.auditEmpty,children:e("profilesLoading")}):null,c==="error"?(0,te.jsx)("div",{style:h.formError,role:"alert",children:D(e,"profilesListFailed",{message:u||""})}):null,c==="empty"?(0,te.jsxs)("div",{style:h.stateWrap,children:[(0,te.jsx)("p",{style:h.stateTitle,children:e("profilesEmpty")}),(0,te.jsx)("p",{style:h.stateDetail,children:e("profilesEmptyHint")}),(0,te.jsx)(Q,{variant:"primary",onClick:()=>Vi(),disabled:p,children:e("profilesNewConnection")})]}):null,r.length>0?(0,te.jsx)("div",{ref:G,style:h.profileList,role:"list","aria-label":e("profilesTitle"),children:B.map(O=>(0,te.jsxs)("div",{style:h.profileSection,children:[(0,te.jsxs)("div",{style:h.profileSectionHeader,children:[(0,te.jsx)("span",{children:O.folder||e("profilesUngrouped")}),(0,te.jsx)("span",{style:h.profileCount,children:D(e,"profilesFolderCount",{count:O.count})})]}),O.items.map(X=>(0,te.jsx)(n_,{profile:X,t:e,busy:p,renaming:y,moving:q,confirmed:k===X.id,highlighted:s===X.id,folderOptions:E,rowRef:ae=>{ae?ke.current.set(X.id,ae):ke.current.delete(X.id)},handlers:Ge},X.id))]},O.folder||"__ungrouped"))}):null]})}var we=require("react");var wh=["send","delay","set","log","expect","if","loop"];var o_=/^[A-Za-z_][A-Za-z0-9_]{0,31}$/,Ko=[{id:"send",labelKey:"tplSend",make:()=>({send:"uptime",enter:!0})},{id:"delay",labelKey:"tplDelay",make:()=>({delay:1e3})},{id:"set",labelKey:"tplSet",make:()=>({set:"target",value:"world"})},{id:"if",labelKey:"tplIf",make:()=>({if:{contains:"error"},then:[{log:'matched "error"'}],else:[{log:"no error seen"}]})},{id:"loop",labelKey:"tplLoop",make:()=>({loop:{count:3,maxIterations:10},steps:[{send:"echo tick",enter:!0},{delay:200}]})},{id:"expect",labelKey:"tplExpect",make:()=>({expect:{match:"ok"},onFail:"stop"})},{id:"log",labelKey:"tplLog",make:()=>({log:"note"})}];function Ch(e){return typeof e!="string"||e===""||!wh.includes(e)?"kindUnknown":`kind${e.charAt(0).toUpperCase()}${e.slice(1)}`}function xh(e,t){let i=Ko.find(c=>c.id===t),s=typeof e=="string"?e:"";if(!i)return{ok:!1,text:s,rebuilt:!1};let r=null,n=!1;if(s.trim()!=="")try{let c=JSON.parse(s);c&&typeof c=="object"&&!Array.isArray(c)?r=c:n=!0}catch{n=!0}r||(r={name:"",description:"",params:{},steps:[]}),Array.isArray(r.steps)||(r.steps=[],n=!0);let o;try{o=i.make()}catch{return{ok:!1,text:s,rebuilt:n}}let l={...r,steps:r.steps.concat([o])};try{return{ok:!0,text:JSON.stringify(l,null,2),rebuilt:n}}catch{return{ok:!1,text:s,rebuilt:n}}}function Ws(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function a_(e){return wh.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function ts(e,t,i,s=0){if(s>8){i.push({path:t,key:"vConditionDeep",params:{max:8}});return}let r=Ws(e);if(!r){i.push({path:t,key:"vCondition"});return}let n=["always","match","contains","variable","not","all","any"].filter(l=>Object.prototype.hasOwnProperty.call(r,l));if(n.length!==1){i.push({path:t,key:"vCondition"});return}let o=n[0];if(o==="always"){r.always!==!0&&i.push({path:t,key:"vCondition"});return}if(o==="match"||o==="contains"){if(typeof r[o]!="string"||r[o]===""){i.push({path:t,key:"vCondition"});return}o==="match"&&!bh(r.match)&&i.push({path:`${t}.match`,key:"vConditionRegex"});return}if(o==="variable"){(typeof r.variable!="string"||r.variable==="")&&i.push({path:t,key:"vCondition"});for(let l of["equals","notEquals","contains","matches"])r[l]!==void 0&&typeof r[l]!="string"&&i.push({path:t,key:"vCondition"});typeof r.matches=="string"&&r.matches!==""&&!bh(r.matches)&&i.push({path:`${t}.matches`,key:"vConditionRegex"});return}if(o==="not"){ts(r.not,`${t}.not`,i,s+1);return}if(!Array.isArray(r[o])||r[o].length===0){i.push({path:t,key:"vConditionList",params:{key:o}});return}r[o].forEach((l,c)=>{ts(l,`${t}.${o}[${c}]`,i,s+1)})}function bh(e){try{return new RegExp(e),!0}catch{return!1}}function Ur(e,t,i,s,r){if(!Array.isArray(e)){s.push({path:t,key:"vSteps"});return}if(i>5){s.push({path:t,key:"vTooDeep",params:{max:5}});return}e.forEach((n,o)=>{r.total+=1,r.total>500&&!r.flagged&&(r.flagged=!0,s.push({path:t,key:"vTooMany",params:{max:500}})),l_(n,`${t}[${o}]`,i,s,r)})}function l_(e,t,i,s,r){let n=Ws(e);if(!n){s.push({path:t,key:"vStepObject"});return}let o=a_(n);if(o.length===0){let a=Object.keys(n);a.length===0?s.push({path:t,key:"vNoKind"}):s.push({path:t,key:"vUnknownKind",params:{kind:a.join("/")}});return}if(o.length>1){s.push({path:t,key:"vMultiKind",params:{kinds:o.join("/")}});return}let l=o[0];if(l==="send"){(typeof n.send!="string"||n.send.trim()==="")&&s.push({path:t,key:"vSend"});return}if(l==="delay"){(typeof n.delay!="number"||!Number.isFinite(n.delay)||n.delay<=0)&&s.push({path:t,key:"vDelay"});return}if(l==="set"){(typeof n.set!="string"||!o_.test(n.set))&&s.push({path:t,key:"vSetName"}),typeof n.value!="string"&&s.push({path:t,key:"vSetValue"});return}if(l==="log"){typeof n.log!="string"&&s.push({path:t,key:"vLog"});return}if(l==="expect"){Ws(n.expect)?ts(n.expect,`${t}.expect`,s):s.push({path:t,key:"vExpect"}),n.onFail!==void 0&&n.onFail!=="stop"&&n.onFail!=="continue"&&s.push({path:t,key:"vExpectOnFail"});return}if(l==="if"){ts(n.if,`${t}.if`,s),Array.isArray(n.then)?n.then.length===0?s.push({path:t,key:"vIfThenEmpty"}):Ur(n.then,`${t}.then`,i+1,s,r):s.push({path:t,key:"vIfThen"}),n.else!==void 0&&(Array.isArray(n.else)?Ur(n.else,`${t}.else`,i+1,s,r):s.push({path:t,key:"vIfElse"}));return}let c=Ws(n.loop);if(!c)s.push({path:t,key:"vLoopCond"});else{let a=c.count!==void 0,u=c.while!==void 0,d=c.until!==void 0;!a&&!u&&!d&&s.push({path:t,key:"vLoopCond"}),a&&(!Number.isInteger(c.count)||c.count<1||c.count>1e3)&&s.push({path:`${t}.loop.count`,key:"vLoopCount",params:{max:1e3}}),u&&ts(c.while,`${t}.loop.while`,s),d&&ts(c.until,`${t}.loop.until`,s),c.maxIterations!==void 0&&(!Number.isInteger(c.maxIterations)||c.maxIterations<1||c.maxIterations>1e3)&&s.push({path:`${t}.loop.maxIterations`,key:"vLoopMax",params:{max:1e3}})}!Array.isArray(n.steps)||n.steps.length===0?s.push({path:t,key:"vLoopBody"}):Ur(n.steps,`${t}.steps`,i+1,s,r)}function kh(e){let t=Ws(e);if(!t)return[{path:"script",key:"vSteps"}];if(!Array.isArray(t.steps))return[{path:"steps",key:"vSteps"}];let i=[],s={total:0,flagged:!1};return Ur(t.steps,"steps",0,i,s),i}var c_=new Set(["raw","wait","set","log","expect","python","end"]);function h_(e){let t=/^(\d+(?:\.\d+)?)\s*(ms|s)?$/i.exec(String(e||"").trim());if(!t)return null;let i=Number(t[1]);if(!Number.isFinite(i)||i<0)return null;let s=(t[2]||"ms").toLowerCase();return Math.round(s==="s"?i*1e3:i)}function Eh(e,t={}){let i=t.waitAfterSend===!0,s=Number.isInteger(t.idleMs)?t.idleMs:250,r=Number.isInteger(t.timeoutMs)?t.timeoutMs:15e3,n=[],o=String(e??"").split(/\r?\n/),l=null,c=(a,u)=>{let d={send:a,enter:u};return i&&u&&(d.waitFor={idleMs:s,timeoutMs:r}),d};for(let a=0;a<o.length;a+=1){let u=o[a],d=u.trim(),_=a+1;if(l!==null){if(d==="@end"){n.push({send:"PY",enter:!0}),l=null;continue}d.length>0&&n.push({send:u,enter:!0});continue}if(d.length===0||d.startsWith("#"))continue;if(!d.startsWith("@")){n.push(c(d,!0));continue}let m=/^@([a-zA-Z]+)\s*([\s\S]*)$/.exec(d),p=m?m[1].toLowerCase():"",g=m?m[2].trim():"";if(!c_.has(p))return{ok:!1,line:_,message:`unknown directive @${p||"?"}`};if(p==="python"){n.push({send:"python3 - <<'PY'",enter:!0}),l={opened:!0};continue}if(p==="end")return{ok:!1,line:_,message:"@end without @python"};if(p==="raw"){if(g.length===0)return{ok:!1,line:_,message:"@raw needs text"};n.push({send:g,enter:!1});continue}if(p==="wait"){let x=h_(g);if(x===null)return{ok:!1,line:_,message:"@wait needs a duration, e.g. @wait 500 or @wait 2s"};n.push({delay:x});continue}if(p==="set"){let x=/^([A-Za-z][A-Za-z0-9_]*)\s*(?:=|\s)\s*([\s\S]*)$/.exec(g);if(!x)return{ok:!1,line:_,message:'@set needs "name = value"'};n.push({set:x[1],value:x[2].trim()});continue}if(p==="log"){if(g.length===0)return{ok:!1,line:_,message:"@log needs text"};n.push({log:g});continue}let y=/^(continue\s+)?([\s\S]+)$/.exec(g);if(!y||y[2].trim().length===0)return{ok:!1,line:_,message:"@expect needs a pattern"};n.push({expect:{match:y[2].trim()},onFail:y[1]?"continue":"stop"})}return l!==null?{ok:!1,line:o.length,message:"@python block is missing @end"}:n.length===0?{ok:!1,line:1,message:"the script has no steps"}:{ok:!0,steps:n}}function Rh(e){if(!Array.isArray(e)||e.length===0)return{ok:!1,reason:"empty"};let t=[],i=null,s=!0;for(let n of e){if(n===null||typeof n!="object")return{ok:!1,reason:"invalid"};if(typeof n.send=="string"){let o=n.waitFor;if(o===void 0)s=!1;else{let l=`${o.idleMs===void 0?"":o.idleMs}/${o.timeoutMs===void 0?"":o.timeoutMs}`;if(i===null)i=l;else if(i!==l)return{ok:!1,reason:"mixedWait"}}if(n.read!==void 0&&n.read!=="delta")return{ok:!1,reason:"read"};if(n.capture!==void 0)return{ok:!1,reason:"capture"};t.push(n.enter===!1?`@raw ${n.send}`:n.send);continue}if(Number.isInteger(n.delay)){t.push(`@wait ${n.delay}`);continue}if(typeof n.set=="string"){t.push(`@set ${n.set} = ${n.value===void 0?"":n.value}`);continue}if(typeof n.log=="string"){t.push(`@log ${n.log}`);continue}if(n.expect!==void 0){if(typeof n.expect.match!="string")return{ok:!1,reason:"condition"};if(n.capture!==void 0)return{ok:!1,reason:"capture"};t.push(`@expect ${n.onFail==="continue"?"continue ":""}${n.expect.match}`);continue}return{ok:!1,reason:"structured"}}let r=s&&i!==null;return{ok:!0,text:t.join(`
|
|
388
|
+
`),waitAfterSend:r}}var Uo=[{id:"cmd",labelKey:"scriptsTemplateCmd",lines:["uname -a"]},{id:"wait",labelKey:"scriptsTemplateWait",lines:["@wait 500"]},{id:"set",labelKey:"scriptsTemplateSet",lines:["@set name = value"]},{id:"log",labelKey:"scriptsTemplateLog",lines:["@log 说明"]},{id:"expect",labelKey:"scriptsTemplateExpect",lines:["@expect ready"]},{id:"python",labelKey:"scriptsTemplatePython",lines:null}];function Lh(e,t){let i=Uo.find(o=>o.id===t);if(!i)return null;let s=i.lines===null?d_.trimEnd().split(`
|
|
389
389
|
`):i.lines,r=typeof e=="string"?e:"";return(r.length===0||r.endsWith(`
|
|
390
390
|
`)?r:r+`
|
|
391
391
|
`)+s.join(`
|
|
392
392
|
`)+`
|
|
393
|
-
`}var
|
|
394
|
-
`);var
|
|
395
|
-
`),
|
|
396
|
-
`));return}let ee=Array.isArray(v.steps)?v.steps:[];if(typeof y.seededFrom=="string"&&y.seededFrom!==""&&ee.length===0&&!ot){let De=r.find(Wt=>Wt.name===y.seededFrom)||null,Ye=De?De.stepCount:0;if(Ye>0){re(!0),le(I(e,"scriptsEmptySaveWarn",{count:Ye}));return}}let ze=String(y.meta.name||"").trim()||(typeof v.name=="string"?v.name.trim():"");if(ze===""){le(e("scriptsNameRequired"));return}let lt={name:ze,description:y.meta.description||(typeof v.description=="string"?v.description:""),folder:y.meta.folder||(typeof v.folder=="string"?v.folder:""),params:v.params&&typeof v.params=="object"&&Object.keys(v.params).length>0?v.params:y.meta.params,steps:ee};W(!0),le(null);try{let De=await Is(lt);if(!Ce.current)return;let Ye=xi(De&&De.script),Wt=Ye?Ye.name:lt.name;ko(Wt,y.mode),G(e("scriptsSaved")),re(!1);let Es=lt.folder;d(Es),M(!1),await Ci(Wt,{openDraft:!0,scope:Es})}catch(De){if(!Ce.current)return;le(oe(De))}finally{Ce.current&&W(!1)}},Tc=()=>{!Ee||we||pt||Z(!0)},Dc=async()=>{if(!(!Ee||we||pt)){Z(!1),k(!0),Y(null);try{let v=Ee;if(await ta(v.name),!Ce.current)return;Yh(v.folder||"",v.name),G(e("scriptsDeleted")),x(null),await Ci("")}catch(v){if(!Ce.current)return;Y(I(e,"scriptsDeleteFailed",{message:oe(v)}))}finally{Ce.current&&k(!1)}}},Bc=async()=>{if(!(!Ee||se||we)){Y(null),W(!0);try{let v=await Ps(Ee.name);if(!Ce.current)return;let H=Ns(v&&v.script);if(!H)throw new Error(I(e,"scriptsGetInvalid",{name:Ee.name}));let ee=new Set(r.map(Wt=>Wt.name)),be=`${Ee.name}-copy`,ze=2;for(;ee.has(be);)be=`${Ee.name}-copy${ze}`,ze+=1;let lt=await Is({name:be,description:H.description,folder:H.folder,params:H.params,steps:H.steps});if(!Ce.current)return;let De=xi(lt&<.script),Ye=De?De.name:be;ko(Ye,kr(Ee.name)),G(I(e,"scriptsCopied",{name:Ye})),await Ci(Ye,{openDraft:!0})}catch(v){if(!Ce.current)return;Y(I(e,"scriptsCopyFailed",{message:oe(v)}))}finally{Ce.current&&W(!1)}}},Ao=v=>{if(!_)return;jh(u,Cs,_,v).moved&&de(ee=>ee+1)},ks=ws.map(v=>v.id).filter(v=>P.includes(v)),Lc=v=>{me(H=>H.includes(v)?H.filter(ee=>ee!==v):[...H,v])},Mo=async()=>{if(!Ee||pt)return;if(ft==="current"&&!t){Y(e("scriptsTargetNoSessions"));return}let v=ws.map(be=>be.id);if(ft==="all"&&v.length===0){Y(e("scriptsTargetNoSessions"));return}if(ft==="selected"&&ks.length===0){Y(e("scriptsTargetPickedEmpty"));return}Y(null),wa(`script:${Ee.name}`);let H={};for(let[be,ze]of Object.entries(Ct))H[be]=ze;let ee={name:Ee.name,params:H};ft==="all"?ee.targets=v:ft==="selected"?ee.targets=ks:ee.sessionId=t;try{let be=await Os(ee);Zr({result:be&&be.result})}catch(be){Zr({error:oe(be)})}},Po=async(v,H)=>{let ee=r.filter(be=>(be.folder||"")===v);for(let be of ee){let ze=await Ps(be.name),lt=Ns(ze&&ze.script);if(!lt)throw new Error(I(e,"scriptsGetInvalid",{name:be.name}));await Is({name:lt.name,description:lt.description,folder:H,params:lt.params,steps:lt.steps})}},Io=()=>{let v=String(L||"").trim().slice(0,64);v!==""&&(p(H=>H.includes(v)?H:H.concat([v])),d(v),g(null),x(null),$(null),T(""),A(!1),G(I(e,"scriptsFolderAdded",{name:v})))},Oo=async()=>{let v=String(B||"").trim().slice(0,64);if(v===""||v===u){M(!1);return}Oe(!0);try{if(await Po(u,v),!Ce.current)return;Gh(u,v),p(H=>H.map(ee=>ee===u?v:ee)),M(!1),d(v),G(e("scriptsFolderRenamed")),await Ci(_,{openDraft:!0,scope:v})}catch(H){G(I(e,"scriptsFolderFailed",{message:oe(H)}))}finally{Ce.current&&Oe(!1)}},Ac=async()=>{if(u){Oe(!0);try{if(await Po(u,""),!Ce.current)return;Xh(u),p(v=>v.filter(H=>H!==u)),ne(!1),d(""),G(e("scriptsFolderDeleted")),await Ci(_,{openDraft:!0,scope:""})}catch(v){G(I(e,"scriptsFolderFailed",{message:oe(v)}))}finally{Ce.current&&Oe(!1)}}},Lr=ws.length,Mc=()=>{if(pt)return I(e,"scriptsResultRunning",{steps:wi.length});if(wi.length===0&&!Fi)return e("scriptsProgressEmpty");let v=[I(e,"scriptsResultDone",{steps:wi.length})];return Fi&&(Fi.timedOut&&v.push(e("scriptsRunTimedOut")),v.push(I(e,"scriptsRunSummary",{runs:Fi.runs.length,ok:Fi.runs.filter(H=>H.ok).length}))),v.filter(Boolean).join(" · ")},R_=u||e("scriptsUngrouped"),T_=Ee?[Ee.description||null,I(e,"scriptsSteps",{count:Ee.stepCount}),I(e,"scriptsParamsCount",{count:Ee.paramCount})].filter(Boolean).join(" · "):"";return(0,w.jsxs)(Si,{title:e("scriptsTitle"),onBack:i,backLabel:e("scriptsPanelClose"),children:[(0,w.jsxs)("div",{style:c.folderBar,children:[(0,w.jsx)("span",{style:c.label,children:e("scriptsFolder")}),(0,w.jsxs)("select",{style:{...c.select,flex:"1 1 120px",width:"auto"},value:u,"aria-label":e("scriptsFolderScope"),disabled:_e,onChange:v=>xc(v.target.value),children:[(0,w.jsx)("option",{value:"",children:e("scriptsUngrouped")}),Tr.map(v=>(0,w.jsx)("option",{value:v,children:v},v))]}),(0,w.jsx)(J,{style:c.rowBtnSmall,onClick:()=>{A(!0),M(!1),ne(!1)},disabled:_e,children:e("scriptsFolderAdd")}),(0,w.jsx)(J,{style:c.rowBtnSmall,onClick:()=>{M(!0),te(u),A(!1),ne(!1)},disabled:!u||_e,children:e("scriptsFolderRename")}),(0,w.jsx)(J,{style:c.rowBtnSmall,variant:"danger",onClick:()=>{ne(!0),M(!1),A(!1)},disabled:!u||_e,children:e("scriptsFolderDelete")})]}),E?(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("input",{style:{...c.input,width:150},value:L,"aria-label":e("scriptsFolderNew"),placeholder:e("scriptsFolderNew"),autoComplete:"off",spellCheck:!1,onChange:v=>T(v.target.value),onKeyDown:v=>{v&&v.key==="Enter"&&Io(),v&&v.key==="Escape"&&(v.stopPropagation(),A(!1))}}),(0,w.jsx)(J,{variant:"primary",onClick:Io,disabled:String(L).trim()==="",children:e("scriptsFolderUse")}),(0,w.jsx)(J,{onClick:()=>A(!1),children:e("cancel")})]}):null,b?(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("input",{style:{...c.input,width:150},value:B,"aria-label":e("scriptsFolderRename"),placeholder:e("scriptsFolderNew"),autoComplete:"off",spellCheck:!1,onChange:v=>te(v.target.value),onKeyDown:v=>{v&&v.key==="Enter"&&Oo(),v&&v.key==="Escape"&&(v.stopPropagation(),M(!1))}}),(0,w.jsx)(J,{variant:"primary",onClick:Oo,disabled:_e,children:e("scriptsFolderUse")}),(0,w.jsx)(J,{onClick:()=>M(!1),children:e("cancel")})]}):null,Se?(0,w.jsx)(ri,{message:I(e,"scriptsFolderDeletePrompt",{name:u}),confirmLabel:e("scriptsFolderDelete"),cancelLabel:e("cancel"),busy:_e,onConfirm:Ac,onCancel:()=>ne(!1)}):null,(0,w.jsxs)("div",{style:c.scriptSplit,children:[(0,w.jsxs)("div",{style:c.scriptListCol,children:[(0,w.jsxs)("div",{style:c.scriptListScroll,role:"listbox","aria-label":e("scriptsTitle"),children:[o==="loading"?(0,w.jsx)("div",{style:c.auditEmpty,children:e("scriptsLoading")}):null,o==="error"?(0,w.jsx)("div",{style:{...c.formError,margin:6},role:"alert",children:I(e,"scriptsListFailed",{message:h||""})}):null,o==="empty"?(0,w.jsxs)("div",{style:c.auditEmpty,children:[e("scriptsEmpty"),(0,w.jsx)("span",{style:{display:"block",fontSize:11},children:e("scriptsEmptyHint")})]}):null,o!=="loading"&&r.length>0&&Do.length===0?(0,w.jsx)("div",{style:c.auditEmpty,children:e("scriptsFolderEmpty")}):null,Do.map(v=>{let H=v.name===_;return(0,w.jsxs)("button",{type:"button",role:"option","aria-selected":H,"aria-label":v.name,title:v.description||v.name,style:{...c.listRow,...H?c.scriptRowActive:null},onClick:()=>Cc(v.name),children:[(0,w.jsx)("span",{style:c.listRowTitle,children:v.name}),(0,w.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0},children:[(0,w.jsx)("span",{style:c.dialectTag,children:kr(v.name)==="macro"?e("scriptsModeMacro"):e("scriptsModeJson")}),(0,w.jsx)("span",{style:c.listRowMeta,children:I(e,"scriptsSteps",{count:v.stepCount})})]})]},v.name)})]}),(0,w.jsxs)("div",{style:{...c.scriptListButtons,position:"relative"},children:[j?(0,w.jsxs)("div",{style:c.newChoicePop,role:"menu","aria-label":e("scriptsNewType"),children:[(0,w.jsx)(J,{style:c.newChoiceOption,onClick:()=>{z(!1),Bo("macro")},disabled:se||C,children:e("scriptsModeMacro")}),(0,w.jsx)(J,{style:c.newChoiceOption,onClick:()=>{z(!1),Bo("json")},disabled:se||C,children:e("scriptsModeJson")})]}):null,(0,w.jsx)(J,{style:c.rowBtnSmall,title:e("scriptsNewAction"),"aria-expanded":j,onClick:()=>z(v=>!v),disabled:se||C,children:`+ ${e("scriptsNewAction")}`}),(0,w.jsx)(J,{style:c.rowBtnSmall,variant:"danger",title:e("scriptsDelete"),onClick:Tc,disabled:!Ee||pt||we,busy:we,children:`− ${e("scriptsDelete")}`}),(0,w.jsx)(J,{style:c.rowBtnSmall,title:e("scriptsMoveUp"),onClick:()=>Ao(-1),disabled:!bc,children:"▲"}),(0,w.jsx)(J,{style:c.rowBtnSmall,title:e("scriptsMoveDown"),onClick:()=>Ao(1),disabled:!wc,children:"▼"}),(0,w.jsx)(J,{style:c.rowBtnSmall,title:e("scriptsCopy"),onClick:Bc,disabled:!Ee||se,children:e("scriptsCopy")})]})]}),(0,w.jsxs)("div",{style:c.scriptEditCol,children:[X?(0,w.jsx)("div",{style:c.formError,role:"alert",children:X}):null,C&&!y?(0,w.jsx)("span",{style:c.hint,children:e("scriptsLoadingEditor")}):null,y?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(Pe,{label:e("scriptsName"),hint:e("scriptsNameHint"),children:(0,w.jsx)("input",{style:c.input,value:y.meta.name,"aria-label":e("scriptsName"),autoComplete:"off",spellCheck:!1,disabled:se,onChange:v=>Lo({name:v.target.value})})}),(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("span",{style:c.label,children:e("scriptsFolder")}),(0,w.jsxs)("select",{style:{...c.select,flex:"1 1 110px",width:"auto"},value:y.meta.folder,"aria-label":e("scriptsFolder"),disabled:se,onChange:v=>Lo({folder:v.target.value}),children:[(0,w.jsx)("option",{value:"",children:e("scriptsUngrouped")}),Tr.map(v=>(0,w.jsx)("option",{value:v,children:v},v)),y.meta.folder&&!Tr.includes(y.meta.folder)?(0,w.jsx)("option",{value:y.meta.folder,children:y.meta.folder}):null]})]}),(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("span",{style:c.label,children:e("scriptsMode")}),(0,w.jsx)("span",{style:c.dialectTag,children:y.mode==="macro"?e("scriptsModeMacro"):e("scriptsModeJson")}),(0,w.jsx)("span",{style:c.hint,children:y.mode==="macro"?e("scriptsMacroHint"):e("scriptsJsonHint")})]}),y.mode==="macro"?(0,w.jsx)("span",{style:c.hint,children:e("scriptsMacroHelp")}):null,(0,w.jsxs)("div",{style:c.templateRow,children:[(0,w.jsx)("span",{style:c.label,children:e("scriptsTemplate")}),(0,w.jsxs)("select",{style:{...c.select,flex:"1 1 120px",width:"auto"},value:"","aria-label":e("scriptsTemplate"),disabled:se,onChange:v=>Ec(v.target.value),children:[(0,w.jsx)("option",{value:"",children:e("scriptsTemplatePlaceholder")}),(y.mode==="macro"?xo:Co).map(v=>(0,w.jsx)("option",{value:v.id,children:e(v.labelKey)},v.id))]})]}),(0,w.jsxs)("div",{style:{...c.field,...c.editorGrow},children:[(0,w.jsx)("span",{style:c.label,children:y.mode==="macro"?e("scriptsModeMacro"):e("scriptsSave")}),(0,w.jsx)("textarea",{style:{...c.textarea,...c.editorBody},value:y.text,spellCheck:!1,autoComplete:"off",onChange:v=>{Br({text:v.target.value}),ot&&re(!1),q&&le(null)},disabled:se})]}),vt?(0,w.jsx)("span",{style:c.hint,children:vt}):null,q?(0,w.jsx)("div",{style:{...c.formError,whiteSpace:"pre-wrap"},role:"alert",children:q}):null,(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)(J,{variant:"primary",onClick:Rc,busy:se,disabled:se,children:e(ot?"scriptsEmptySaveConfirm":"scriptsSaveAction")}),(0,w.jsx)(J,{onClick:kc,disabled:se,children:e("scriptsCancel")})]})]}):C?null:(0,w.jsx)("div",{style:c.stateWrap,children:(0,w.jsx)("p",{style:c.stateDetail,children:e("scriptsEditorEmpty")})})]})]}),fe?(0,w.jsx)(ri,{message:I(e,"scriptsDeletePrompt",{name:Ee?Ee.name:""}),confirmLabel:e("scriptsDeleteConfirm"),cancelLabel:e("cancel"),busy:we,onConfirm:Dc,onCancel:()=>Z(!1)}):null,Ee?(0,w.jsxs)("div",{style:c.runSection,children:[(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("span",{style:c.sectionTitle,children:e("scriptsTarget")}),(0,w.jsx)(Sr,{label:e("scriptsTarget"),value:ft,disabled:pt,options:[{value:"current",label:e("scriptsTargetCurrent"),hint:e("scriptsTargetCurrent")},{value:"selected",label:e("scriptsTargetPicked"),hint:e("scriptsTargetPickedHint")},{value:"all",label:e("scriptsTargetAll"),hint:I(e,"scriptsTargetAllHint",{count:Lr})}],onChange:bi}),(0,w.jsx)("span",{style:c.hint,children:ft==="all"?I(e,"scriptsTargetAllHint",{count:Lr}):ft==="selected"?I(e,"scriptsTargetPickedHint",{count:ks.length}):t||"—"})]}),ft==="selected"?(0,w.jsx)("div",{style:c.pickList,role:"group","aria-label":e("scriptsTargetPicked"),children:Lr===0?(0,w.jsx)("span",{style:c.hint,children:e("scriptsTargetNoSessions")}):ws.map(v=>{let H=ks.includes(v.id);return(0,w.jsxs)("label",{style:c.pickRow,children:[(0,w.jsx)("input",{type:"checkbox",checked:H,disabled:pt,onChange:()=>Lc(v.id),style:c.pickBox}),(0,w.jsx)("span",{style:c.pickTitle,children:v.title}),(0,w.jsx)("span",{style:c.pickMeta,children:u_(v)})]},v.id)})}):null,Ee.paramCount>0?(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)("span",{style:c.sectionTitle,children:e("scriptsParams")}),Object.entries(Ee.params).map(([v,H])=>(0,w.jsx)(Pe,{label:v,hint:H&&H.description?H.description:void 0,children:(0,w.jsx)("input",{style:c.input,value:Ct[v]===void 0?"":Ct[v],placeholder:H&&H.default?H.default:"",autoComplete:"off",spellCheck:!1,onChange:ee=>{let be={...Ct,[v]:ee.target.value};oi(be)},onKeyDown:ee=>{ee&&ee.key==="Enter"&&Mo()},disabled:pt})},v))]}):(0,w.jsx)("span",{style:c.hint,children:e("scriptsNoParams")}),(0,w.jsxs)("div",{style:c.actionRow,children:[(0,w.jsx)(J,{variant:"primary",onClick:Mo,disabled:pt||!Ee,children:e(pt?"scriptsRunning":"scriptsRun")}),(0,w.jsx)("span",{style:{...c.resultSummary,flex:"1 1 140px"},children:Mc()}),(0,w.jsx)(J,{onClick:()=>Ae(!0),title:e("scriptsResultTitle"),children:e("scriptsViewResult")})]}),D?(0,w.jsx)("div",{style:c.formError,role:"alert",children:D}):null,at.state==="done"&&!D&&at.error?(0,w.jsx)("div",{style:c.formError,role:"alert",children:I(e,"scriptsRunFailed",{message:at.error})}):null]}):null,Ne?(0,w.jsx)(Ih,{title:e("scriptsResultTitle"),closeLabel:e("scriptsResultClose"),onClose:()=>Ae(!1),children:(0,w.jsx)("div",{ref:qe,style:c.resultBox,role:"log","aria-label":e("scriptsRun"),children:wi.length===0?(0,w.jsx)("div",{style:c.auditEmpty,children:e("scriptsProgressEmpty")}):wi.map(v=>(0,w.jsx)(p_,{line:v,t:e},v.key))})}):null]})}var R=require("react/jsx-runtime");function gc(e){return typeof e=="function"?e:t=>t}function Ro(e){return!e.sessions||e.sessions.length===0?null:e.sessions.find(i=>i.id===e.selectedId)||e.sessions[0]}function vc({t:e,sessionId:t}){let i=gc(e),s=Bt(),r=Ro(s);if((0,Le.useEffect)(()=>{Ks(t)},[t]),(0,Le.useEffect)(()=>(Qr(),Ui().catch(()=>{}),()=>ka()),[]),(0,Le.useEffect)(()=>{r&&s.selectedId!==r.id&&hi(r.id)},[r?r.id:null,s.selectedId]),(0,Le.useEffect)(()=>{if(typeof document>"u"||typeof document.addEventListener!="function")return;let h=a=>{!a||a.key!=="Escape"||a.defaultPrevented||Xr()&&typeof a.preventDefault=="function"&&a.preventDefault()};return document.addEventListener("keydown",h),()=>{try{document.removeEventListener("keydown",h)}catch{}}},[]),!s.ready&&s.sessions.length===0)return(0,R.jsxs)("div",{style:c.root,children:[(0,R.jsx)("div",{style:{...c.stateWrap,flex:1},children:i("loading")}),(0,R.jsx)(So,{toast:s.toast})]});let n=!r&&s.view!=="connect",o=s.view==="connect"||!r,l=r&&s.resets&&s.resets[r.id]||null;return(0,R.jsxs)("div",{style:c.root,children:[(0,R.jsx)(__,{t:i}),o?(0,R.jsx)(ec,{t:i,draft:s.connectDraft,onCancel:Sa()?()=>Jr():void 0,onSaved:h=>Jr(h)},s.connectDraft&&s.connectDraft.id?`edit:${s.connectDraft.id}`:"new"):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(v_,{t:i,session:r}),(0,R.jsx)(y_,{t:i,session:r,reset:l},r.id)]}),!o&&s.panel==="history"?(0,R.jsx)(sc,{t:i,sessionId:r?r.id:null,onClose:ci}):null,!o&&s.panel==="scripts"?(0,R.jsx)(mc,{t:i,sessionId:r?r.id:null,onClose:ci}):null,n||!o&&s.panel==="profiles"?(0,R.jsx)(nc,{t:i,onClose:n?void 0:ci}):null,(0,R.jsx)(So,{toast:s.toast})]})}function __({t:e}){let t=Bt(),[i,s]=(0,Le.useState)(null),[r,n]=(0,Le.useState)(!1),o=t.panel==="profiles",l=()=>{o?ci():$s("profiles")},h=i&&t.sessions.find(g=>g.id===i)||null,a=Ro(t),u=a?a.id:null,d=new Map;for(let g of t.sessions){let y=g.title||"";d.set(y,(d.get(y)||0)+1)}let m=new Map,p=g=>{let y=g.title||"";if((d.get(y)||0)<2)return y;let x=(m.get(y)||0)+1;return m.set(y,x),`${y} #${x}`},_=async g=>{if(!r){n(!0),Ri(g);try{await pe("sessions.close",{id:g})}catch(y){G(I(e,"closeFailed",{message:oe(y)}))}finally{n(!1),s(null)}}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:c.rail,role:"tablist","aria-label":e("sessions"),children:[t.sessions.map(g=>{let y=g.id===u,x=g.state==="disconnected",j=p(g);return(0,R.jsx)(m_,{t:e,session:g,label:j,active:y,disconnected:x,onSelect:()=>hi(g.id),onRequestClose:()=>s(g.id)},g.id)}),(0,R.jsx)("span",{style:c.railSpacer}),(0,R.jsxs)(J,{variant:o?"outline":"default",title:e("profiles"),ariaLabel:e("profiles"),onClick:l,style:{height:32,padding:"0 8px"},children:[(0,R.jsx)($h,{}),e("profiles")]}),(0,R.jsx)("button",{type:"button",style:c.railAdd,title:e("newSession"),"aria-label":e("newSession"),onClick:()=>Ti(),children:(0,R.jsx)(Nh,{})})]}),h?(0,R.jsx)("div",{style:c.railConfirmWrap,children:(0,R.jsx)(ri,{message:I(e,"closeSessionPrompt",{title:h.title}),confirmLabel:e("closeConfirm"),cancelLabel:e("cancel"),busy:r,onConfirm:()=>_(h.id),onCancel:()=>s(null)})}):null]})}function m_({t:e,session:t,label:i,active:s,disconnected:r,onSelect:n,onRequestClose:o}){let{focus:l,focusProps:h}=vs(),[a,u]=(0,Le.useState)(!1),d={...c.railChip,...s?c.railChipActive:null,...!s&&a?c.railChipHover:null,...l?{boxShadow:Pi(!0)}:null};return(0,R.jsxs)("div",{role:"presentation",style:d,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),children:[(0,R.jsxs)("button",{type:"button",role:"tab","aria-selected":s,title:`${i} · ${t.username?`${t.username}@`:""}${t.host}${t.port?`:${t.port}`:""}${r?` · ${e("stateDisconnected")}`:""}`,onClick:n,style:{display:"inline-flex",alignItems:"center",gap:6,minWidth:0,height:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",fontSize:13,lineHeight:1,fontWeight:s?600:400,cursor:"pointer",outline:"none"},...h,children:[(0,R.jsx)(Ph,{state:t.state}),(0,R.jsx)("span",{style:r?c.railTitleDim:c.railTitle,children:i}),(0,R.jsx)("span",{style:{...c.transportBadge,...t.transport==="telnet"?c.transportBadgeTelnet:c.transportBadgeSsh},children:t.transport})]}),(0,R.jsx)(Pt,{size:26,danger:!0,title:e("closeSession"),onClick:o,children:(0,R.jsx)(ys,{size:12})})]})}var g_=[{value:"ro",labelKey:"permRo",hintKey:"permRoHint"},{value:"wo",labelKey:"permWo",hintKey:"permWoHint"},{value:"rw",labelKey:"permRw",hintKey:"permRwHint"}];function v_({t:e,session:t}){let s=Bt().panel,r=t.permission,[n,o]=(0,Le.useState)(()=>Date.now()),[l,h]=(0,Le.useState)(!1),[a,u]=(0,Le.useState)(null),[d,m]=(0,Le.useState)(!1),[p,_]=(0,Le.useState)(!1),[g,y]=(0,Le.useState)(!1),x=(0,Le.useRef)(null),j=(0,Le.useRef)(null);(0,Le.useEffect)(()=>{let B=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(B)},[]),(0,Le.useEffect)(()=>{h(!1),m(!1),u(null)},[t.id]);let z=t.state==="closed"||t.state==="failed",C=t.state==="disconnected",O=C||t.state==="failed",X=t.state==="open",$=a==="reconnect"||t.reconnecting===!0,ye=r.lockOwner,de=ye==="ai"&&r.lockExpiresAt?Math.max(0,Math.ceil((r.lockExpiresAt-n)/1e3)):null,fe=e(ye==="ai"?"lockAi":ye==="human"?"lockHuman":"lockFree"),Z=ye==="ai"?f.warn:ye==="human"?f.success:f.labelTertiary,we=async B=>{if(!a){u("access");try{let te=await pe("permission.set",{id:t.id,aiAccess:B});Vi(t.id,te&&te.permission),G(e("accessChanged"))}catch(te){G(I(e,"accessFailed",{message:oe(te)}))}finally{u(null)}}},k=async()=>{if(!a){u("lock");try{let B=await pe("lock.takeOver",{id:t.id});Vi(t.id,B&&B.permission),G(e("takenOver"))}catch(B){G(I(e,"takeOverFailed",{message:oe(B)}))}finally{u(null)}}},E=async()=>{if(!a){u("lock");try{let B=await pe("lock.release",{id:t.id});Vi(t.id,B&&B.permission),G(e("released"))}catch(B){G(I(e,"releaseFailed",{message:oe(B)}))}finally{u(null)}}},A=async()=>{if(!p){_(!0),Ri(t.id);try{await pe("sessions.close",{id:t.id})}catch(B){G(I(e,"closeFailed",{message:oe(B)}))}finally{_(!1),m(!1)}}},L=async()=>{if(!g){if(C){G(e("copyScreenUnavailable"));return}y(!0);try{let B=await Go(t.id,{changedOnly:!1}),te=oa(B);if(!te.text){G(e("copyScreenEmpty"));return}let Se=await Fs(te.text,j.current);G(e(Se?"copyScreenDone":"copyFailed"))}catch(B){G(I(e,"copyScreenFailed",{message:oe(B)}))}finally{y(!1)}}},T=async()=>{if(!(a||!X)){u("disconnect");try{let B=await $o(t.id);B&&B.session&&Lt(B.session),G(e("disconnectedNotice"))}catch(B){G(I(e,"disconnectFailed",{message:oe(B)}))}finally{u(null)}}},b=async()=>{if(!a){u("reconnect");try{let B=va(t.id)||{cols:t.cols,rows:t.rows},te=await Ko(t.id,B),Se=te&&te.session?Lt(te.session):null;Se&&Se.state==="failed"?G(I(e,"reconnectFailed",{message:Se.error||e("unknownError")})):Se&&Se.state==="open"&&G(e("reconnected"))}catch(B){G(I(e,"reconnectFailed",{message:oe(B)}))}finally{u(null)}}},M=B=>{s===B?ci():$s(B)};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{ref:j,style:{...c.controlBar,position:"relative"},children:[(0,R.jsx)(Sr,{label:e("permission"),value:r.aiAccess,disabled:z||a!==null,options:g_.map(B=>({value:B.value,label:e(B.labelKey),hint:e(B.hintKey)})),onChange:we}),(0,R.jsxs)("span",{style:{...c.lockChip,color:Z},title:`${e("lockFree")} / ${e("lockAi")} / ${e("lockHuman")}`,children:[ye?(0,R.jsx)(wo,{}):(0,R.jsx)("span",{style:{...c.lockDot,background:Z}}),(0,R.jsx)("span",{children:fe}),de!==null?(0,R.jsxs)("span",{style:{color:f.labelTertiary},children:["· ",I(e,"lockAiCountdown",{seconds:de})]}):null]}),(0,R.jsx)("div",{style:c.controlSpacer}),O?(0,R.jsxs)(J,{title:e("reconnectAction"),ariaLabel:e($?"reconnectingAction":"reconnectAction"),onClick:b,busy:$,disabled:a!==null,children:[(0,R.jsx)(qh,{size:14}),e("reconnectAction")]}):ye==="human"?(0,R.jsx)(J,{onClick:E,disabled:a!==null,children:e("releaseAi")}):(0,R.jsx)(J,{onClick:k,disabled:a!==null||z,children:e("takeOver")}),X?(0,R.jsx)(Pt,{danger:!0,title:e("disconnect"),ariaLabel:e("disconnectHint"),disabled:a!==null||t.reconnecting===!0,onClick:T,children:a==="disconnect"?(0,R.jsx)("span",{style:{fontSize:12},children:"…"}):(0,R.jsx)(Uh,{})}):null,(0,R.jsx)(Pt,{active:s==="history",title:e("history"),onClick:()=>M("history"),children:(0,R.jsx)(Wh,{})}),(0,R.jsx)(Pt,{active:s==="scripts",title:e("scripts"),onClick:()=>M("scripts"),children:(0,R.jsx)(zh,{})}),(0,R.jsx)(Pt,{title:e(C?"copyScreenUnavailable":"copyScreen"),disabled:g||C,onClick:L,children:g?(0,R.jsx)("span",{style:{fontSize:12},children:"…"}):(0,R.jsx)(Kh,{})}),(0,R.jsxs)("div",{ref:x,style:{position:"relative",display:"inline-flex",flex:"none"},children:[(0,R.jsxs)(Pt,{active:l,title:e("audit"),onClick:()=>h(B=>!B),children:[(0,R.jsx)(Fh,{}),(0,R.jsx)(Hh,{open:l})]}),(0,R.jsx)(tc,{t:e,sessionId:t.id,open:l,onClose:()=>h(!1),rootRef:x})]}),(0,R.jsx)(Pt,{danger:!0,title:e("closeSession"),onClick:()=>m(!0),children:(0,R.jsx)(ys,{})})]}),d?(0,R.jsx)("div",{style:c.railConfirmWrap,children:(0,R.jsx)(ri,{message:I(e,"closeSessionPrompt",{title:t.title}),confirmLabel:e("closeConfirm"),cancelLabel:e("cancel"),busy:p,onConfirm:A,onCancel:()=>m(!1)})}):null]})}function y_({t:e,session:t,reset:i}){let[s,r]=(0,Le.useState)("connecting"),[n,o]=(0,Le.useState)(!1),l=!!t.permission.humanWriteBlocked,h=t.state==="closed"||t.state==="failed",a=t.state==="disconnected";return(0,R.jsxs)("div",{style:c.pane,children:[l&&!h&&!a?(0,R.jsx)(b_,{t:e,session:t}):null,a?(0,R.jsx)(S_,{t:e,session:t}):null,h?(0,R.jsx)(w_,{t:e,session:t}):null,(0,R.jsx)("div",{style:c.termWrap,children:(0,R.jsx)(Mh,{t:e,session:t,onLinkChange:r,reset:i})}),(0,R.jsx)(Zh,{t:e,sessionId:h||a?null:t.id,open:n,onToggle:()=>o(u=>!u),onOpenLibrary:()=>$s("scripts")}),(0,R.jsx)(C_,{t:e,session:t,link:s})]})}function S_({t:e,session:t}){return(0,R.jsx)("div",{style:{...c.banner,borderLeftColor:f.warn},role:"status",children:(0,R.jsxs)("span",{style:c.bannerText,children:[e("disconnectedTitle"),(0,R.jsx)("span",{style:c.bannerHint,children:e("disconnectedHint")}),t.closeReason?(0,R.jsx)("span",{style:c.bannerHint,children:I(e,"closedReason",{reason:t.closeReason})}):null]})})}function b_({t:e,session:t}){let[i,s]=(0,Le.useState)(!1),r=async()=>{if(!i){s(!0);try{let n=await pe("lock.takeOver",{id:t.id});Vi(t.id,n&&n.permission),G(e("takenOver"))}catch(n){G(I(e,"takeOverFailed",{message:oe(n)}))}finally{s(!1)}}};return(0,R.jsxs)("div",{style:c.banner,role:"status",children:[(0,R.jsx)(wo,{size:12}),(0,R.jsxs)("span",{style:c.bannerText,children:[e("blockedTitle"),(0,R.jsx)("span",{style:c.bannerHint,children:e("blockedHint")})]}),(0,R.jsx)(J,{variant:"primary",onClick:r,busy:i,disabled:i,children:e("takeOver")})]})}function w_({t:e,session:t}){let i=t.state==="failed",[s,r]=(0,Le.useState)(!1),n=async()=>{if(!s){r(!0);try{await pe("sessions.close",{id:t.id})}catch{}finally{r(!1),Ri(t.id,t.error)}}};return(0,R.jsxs)("div",{style:{...c.banner,borderLeftColor:i?f.danger:f.labelTertiary},role:"status",children:[(0,R.jsxs)("span",{style:c.bannerText,children:[e(i?"failedTitle":"closedTitle"),t.error?(0,R.jsx)("span",{style:c.bannerHint,children:I(e,"closedReason",{reason:t.error})}):null]}),(0,R.jsx)(J,{onClick:n,busy:s,disabled:s,children:e("closeSession")})]})}function C_({t:e,session:t,link:i}){let s=t.state==="open"?"stateOpen":t.state==="disconnected"?"stateDisconnected":t.state==="closed"?"stateClosed":t.state==="failed"?"stateFailed":"stateConnecting",r=t.reconnecting===!0||t.state==="open"&&i==="error",n=t.state==="failed"?f.danger:r||t.state==="disconnected"?f.warnLabel:f.labelTertiary,o=`${t.transport==="telnet"?"telnet":"ssh"} ${t.username?`${t.username}@`:""}${t.host}${t.port?`:${t.port}`:""}`;return(0,R.jsxs)("div",{style:c.statusBar,children:[(0,R.jsx)("span",{style:{...c.statusItem,color:n},children:e(r?"reconnecting":s)}),(0,R.jsx)("span",{style:c.statusItem,children:o}),(0,R.jsx)("span",{style:c.controlSpacer}),(0,R.jsx)("span",{style:c.statusItem,children:I(e,"statusSize",{cols:t.cols,rows:t.rows})}),(0,R.jsx)("span",{style:c.statusItem,children:I(e,"statusBytes",{in:li(t.bytesIn),out:li(t.bytesOut)})})]})}function yc({t:e}){let t=gc(e),i=Bt(),s=Ro(i);return(0,R.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,minWidth:0,maxWidth:220},children:[(0,R.jsx)(Oh,{size:12}),s?(0,R.jsx)("span",{style:{...c.transportBadge,...s.transport==="telnet"?c.transportBadgeTelnet:c.transportBadgeSsh},children:s.transport}):null,(0,R.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s?s.title:t("title")})]})}var Er="dsh-aiterm",Rr="aiterm",x_=["slots","locale","sidebarRight","sidebarRightTabs"];function k_(e){let t=e.locale.bind(Wi);e.effect(()=>e.locale.register(Wi,{zh:No,en:Fo}),"aiterm: locale"),e.effect(()=>e.sidebarRightTabs.register({id:Er,kind:Rr,multiple:!1,priority:"extension",title:()=>t("title"),guide:[{id:"open",order:30,title:()=>t("title"),description:()=>t("guide")}]}),"aiterm: tab type");for(let i of[Er,Rr])e.effect(()=>e.slots.inject("sidebar.right.pane.tab",()=>e.slots.register({name:"sidebar.right.pane.tab",key:i,locale:Wi,inject:s=>({sessionId:s})},vc)),`aiterm: pane body (${i})`),e.effect(()=>e.slots.inject("sidebar.right.pane.tab.title",()=>e.slots.register({name:"sidebar.right.pane.tab.title",key:i,locale:Wi,inject:s=>({sessionId:s})},yc)),`aiterm: pane title (${i})`);try{globalThis.__DSH_AITERM_CLIENT__={plugin:Er,kind:Rr,route:"/aiterm",version:"0.5.0",internals:{applyReset:yr,createResetTracker:vr,resetNotice:go,buildReconnectPayload:Or,getState:Ws,setOwner:Ks}}}catch{}}
|
|
393
|
+
`}var d_=["# 用远端 shell 里的 python3 跑一段逻辑(脚本本身仍是纯数据)","hostname","@python","import socket, os",'print("host:", socket.gethostname())','print("cwd :", os.getcwd())',"@end","@wait 500",""].join(`
|
|
394
|
+
`);var Th="dsh.aiterm.scriptDialect";function Dh(){try{let e=globalThis.localStorage&&globalThis.localStorage.getItem(Th);if(!e)return{};let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function qr(e){return Dh()[e]==="json"?"json":"macro"}function qo(e,t){if(!(typeof e!="string"||e===""))try{if(!globalThis.localStorage)return;let i=Dh();i[e]=t==="json"?"json":"macro",globalThis.localStorage.setItem(Th,JSON.stringify(i))}catch{}}var C=require("react/jsx-runtime"),u_=200,Vo=3,f_=["# 每行一条命令,例如:","uname -a","@wait 300",""].join(`
|
|
395
|
+
`),p_={name:"",description:"",folder:"",params:{},steps:[]};function __(e){let t=e.username?`${e.username}@`:"",i=e.port?`:${e.port}`:"";return`${t}${e.host}${i}`}function m_(e){try{return JSON.stringify({name:e.name,description:e.description,folder:e.folder,params:e.params,steps:e.steps},null,2)}catch{return""}}function g_({line:e,t}){let i=e.ok?e.text:e.error||e.text,s=dn(hn(i),u_),n=[dn(hn(i),500),e.code].filter(Boolean).join(" · "),o=Number.isInteger(e.depth)&&e.depth>0?e.depth:0,l=e.path?e.path:`#${e.stepIndex}`;return(0,C.jsxs)("div",{style:h.batchLine,title:n||void 0,children:[(0,C.jsx)("span",{style:h.batchPath,children:`${" ".repeat(o)}${l}`}),(0,C.jsx)("span",{style:h.batchSep,children:"·"}),(0,C.jsx)("span",{style:h.batchKind,children:t(Ch(e.kind))}),(0,C.jsx)("span",{style:h.batchSep,children:"·"}),(0,C.jsx)("span",{style:{flex:"none",color:e.ok?f.success:f.danger},children:e.ok?"✓":"✗"}),(0,C.jsx)("span",{style:h.batchSession,children:e.sessionId}),(0,C.jsx)("span",{style:h.batchText,children:s||"—"})]})}function Ah({t:e,sessionId:t,onClose:i}){let s=zt(),[r,n]=(0,we.useState)([]),[o,l]=(0,we.useState)("loading"),[c,a]=(0,we.useState)(null),[u,d]=(0,we.useState)(""),[_,m]=(0,we.useState)([]),[p,g]=(0,we.useState)(null),[y,x]=(0,we.useState)(null),[q,W]=(0,we.useState)(!1),[k,M]=(0,we.useState)(!1),[Z,K]=(0,we.useState)(null),[ye,ce]=(0,we.useState)(0),[he,G]=(0,we.useState)(!1),[ke,R]=(0,we.useState)(!1),[E,B]=(0,we.useState)(!1),[A,T]=(0,we.useState)(""),[w,I]=(0,we.useState)(!1),[P,re]=(0,we.useState)(""),[Re,ee]=(0,we.useState)(!1),[fe,Ge]=(0,we.useState)(!1),[le,O]=(0,we.useState)(!1),[X,ae]=(0,we.useState)(null),[kt,Ke]=(0,we.useState)(null),[ut,ie]=(0,we.useState)(!1),[Bt,Et]=(0,we.useState)({}),[ft,Ze]=(0,we.useState)("current"),[Si,jt]=(0,we.useState)([]),[$,pe]=(0,we.useState)(null),[Ue,Qe]=(0,we.useState)(!1),Oe=(0,we.useRef)(null),Ee=(0,we.useRef)(!0),De=s&&s.batch?s.batch:Ui(),pt=De.state==="running"||De.pending,oi=(s&&Array.isArray(s.sessions)?s.sessions:[]).filter(v=>v&&v.state==="open"),Ce=r.find(v=>v.name===p)||null,qe=Array.isArray(De.lines)?De.lines:[],Mt=De.runs||null,is=[...new Set([...r.map(v=>v.folder||"").filter(v=>v!==""),..._])].sort((v,z)=>v.localeCompare(z)),bi=r.filter(v=>(v.folder||"")===u),wi=bi.map(v=>v.name),Ci=es(u,wi),zs=Ci.map(v=>bi.find(z=>z.name===v)).filter(Boolean),ss=p?Ci.indexOf(p):-1,$s=ss>0,Ks=ss>=0&&ss<Ci.length-1;async function ai(v,z={}){l("loading"),a(null);try{let se=await Qs();if(!Ee.current)return;let xe=se&&Array.isArray(se.scripts)?se.scripts.map($i).filter(Boolean):[];n(xe),l(xe.length>0?"ready":"empty");let Ve=[...new Set([...xe.map(Wt=>Wt.folder||"").filter(Wt=>Wt!==""),..._])].sort((Wt,Nh)=>Wt.localeCompare(Nh)),gt=typeof z.scope=="string"?z.scope:u,Me=xe.some(Wt=>(Wt.folder||"")===""),et=gt;gt!==""&&!Ve.includes(gt)&&(et=""),et===""&&!Me&&Ve.length>0&&(et=Ve[0]),d(et);let Zt=xe.filter(Wt=>(Wt.folder||"")===et),Vs=typeof v=="string"&&v!==""?v:p,rs=Zt.find(Wt=>Wt.name===Vs)||Zt[0]||null;g(rs?rs.name:null),G(!1),z.openDraft===!0?await xi(rs?rs.name:null):rs||x(null)}catch(se){if(!Ee.current)return;a(ne(se)),l("error")}}async function xi(v){if(!v){x(null),K(null),M(!1);return}M(!0),K(null),ae(null),Ke(null),ie(!1);try{let z=await er(v);if(!Ee.current)return;let se=sr(z&&z.script);if(!se){x(null),K(D(e,"scriptsGetInvalid",{name:v}));return}let xe=Rh(se.steps),Ve=qr(se.name)==="json"||xe.ok!==!0?"json":"macro";x({mode:Ve,seededFrom:se.name,meta:{name:se.name,description:typeof se.description=="string"?se.description:"",folder:typeof se.folder=="string"?se.folder:"",params:se.params&&typeof se.params=="object"?se.params:{}},text:Ve==="json"?m_(se):xe.text})}catch(z){if(!Ee.current)return;x(null),K(D(e,"scriptsGetFailed",{message:ne(z)}))}finally{Ee.current&&M(!1)}}(0,we.useEffect)(()=>(Ee.current=!0,ai(void 0,{openDraft:!0}),()=>{Ee.current=!1}),[]),(0,we.useEffect)(()=>{let v={};if(Ce)for(let[z,se]of Object.entries(Ce.params||{}))v[z]=se&&typeof se.default=="string"?se.default:"";Et(v)},[p,r]),(0,we.useEffect)(()=>{(De.state==="running"||De.pending)&&Qe(!0)},[De.state,De.pending]),(0,we.useEffect)(()=>{let v=Oe.current;v&&(v.scrollTop=v.scrollHeight)},[qe.length,De.state,Ue]);let Us=v=>{v===p&&y||(g(v),pe(null),G(!1),ee(!1),xi(v))},Yr=v=>{d(v),G(!1),ee(!1),I(!1),B(!1);let z=r.filter(Ve=>(Ve.folder||"")===v),se=es(v,z.map(Ve=>Ve.name)),xe=se.length>0?se[0]:null;g(xe),pe(null),xe?xi(xe):(x(null),K(null))},qs=(v="macro")=>{le||k||(g(null),ae(null),Ke(null),ie(!1),K(null),G(!1),pe(null),x({mode:v,seededFrom:null,meta:{name:"",description:"",folder:u,params:{}},text:v==="macro"?f_:JSON.stringify(p_,null,2)}))},Gr=()=>{ae(null),Ke(null),ie(!1),y&&y.seededFrom?xi(y.seededFrom):x(null)},S=v=>{x(z=>z&&{...z,...v})},V=v=>{x(z=>z&&{...z,meta:{...z.meta,...v}})},j=v=>{if(!(!v||le||!y)){if(y.mode==="macro"){let z=Lh(y.text,v);z!==null&&(S({text:z}),ae(null),ie(!1),Ke(null));return}try{let z=xh(y.text,v);if(!z||z.ok!==!0)return;S({text:z.text}),ae(null),ie(!1),Ke(z.rebuilt?e("scriptsTemplateRebuilt"):null)}catch(z){ae(ne(z))}}},_e=async()=>{if(le||!y)return;let v;if(y.mode==="macro"){let Me=Eh(y.text);if(Me.ok!==!0){ae(D(e,"scriptsMacroParseError",{line:Me.line,message:Me.message}));return}v={steps:Me.steps}}else try{v=JSON.parse(y.text)}catch(Me){ae(D(e,"scriptsJsonInvalid",{message:ne(Me)}));return}if(!v||typeof v!="object"||Array.isArray(v)){ae(e("scriptsJsonObject"));return}let z;try{z=kh(v)}catch(Me){ae(ne(Me));return}if(z.length>0){let Me=z.slice(0,Vo).map(et=>D(e,"scriptsValidateAt",{path:et.path,message:D(e,et.key,et.params)}));z.length>Vo&&Me.push(D(e,"scriptsValidateMore",{count:z.length-Vo})),ae(Me.join(`
|
|
396
|
+
`));return}let se=Array.isArray(v.steps)?v.steps:[];if(typeof y.seededFrom=="string"&&y.seededFrom!==""&&se.length===0&&!ut){let Me=r.find(Zt=>Zt.name===y.seededFrom)||null,et=Me?Me.stepCount:0;if(et>0){ie(!0),ae(D(e,"scriptsEmptySaveWarn",{count:et}));return}}let Ve=String(y.meta.name||"").trim()||(typeof v.name=="string"?v.name.trim():"");if(Ve===""){ae(e("scriptsNameRequired"));return}let gt={name:Ve,description:y.meta.description||(typeof v.description=="string"?v.description:""),folder:y.meta.folder||(typeof v.folder=="string"?v.folder:""),params:v.params&&typeof v.params=="object"&&Object.keys(v.params).length>0?v.params:y.meta.params,steps:se};O(!0),ae(null);try{let Me=await tr(gt);if(!Ee.current)return;let et=$i(Me&&Me.script),Zt=et?et.name:gt.name;qo(Zt,y.mode),J(e("scriptsSaved")),ie(!1);let Vs=gt.folder;d(Vs),I(!1),await ai(Zt,{openDraft:!0,scope:Vs})}catch(Me){if(!Ee.current)return;ae(ne(Me))}finally{Ee.current&&O(!1)}},Le=()=>{!Ce||ke||pt||G(!0)},mt=async()=>{if(!(!Ce||ke||pt)){G(!1),R(!0),pe(null);try{let v=Ce;if(await ma(v.name),!Ee.current)return;ch(v.folder||"",v.name),J(e("scriptsDeleted")),x(null),await ai("")}catch(v){if(!Ee.current)return;pe(D(e,"scriptsDeleteFailed",{message:ne(v)}))}finally{Ee.current&&R(!1)}}},Ht=async()=>{if(!(!Ce||le||ke)){pe(null),O(!0);try{let v=await er(Ce.name);if(!Ee.current)return;let z=sr(v&&v.script);if(!z)throw new Error(D(e,"scriptsGetInvalid",{name:Ce.name}));let se=new Set(r.map(Zt=>Zt.name)),xe=`${Ce.name}-copy`,Ve=2;for(;se.has(xe);)xe=`${Ce.name}-copy${Ve}`,Ve+=1;let gt=await tr({name:xe,description:z.description,folder:z.folder,params:z.params,steps:z.steps});if(!Ee.current)return;let Me=$i(gt&>.script),et=Me?Me.name:xe;qo(et,qr(Ce.name)),J(D(e,"scriptsCopied",{name:et})),await ai(et,{openDraft:!0})}catch(v){if(!Ee.current)return;pe(D(e,"scriptsCopyFailed",{message:ne(v)}))}finally{Ee.current&&O(!1)}}},Hi=v=>{if(!p)return;lh(u,Ci,p,v).moved&&ce(se=>se+1)},_t=oi.map(v=>v.id).filter(v=>Si.includes(v)),Wi=v=>{jt(z=>z.includes(v)?z.filter(se=>se!==v):[...z,v])},Yo=async()=>{if(!Ce||pt)return;if(ft==="current"&&!t){pe(e("scriptsTargetNoSessions"));return}let v=oi.map(xe=>xe.id);if(ft==="all"&&v.length===0){pe(e("scriptsTargetNoSessions"));return}if(ft==="selected"&&_t.length===0){pe(e("scriptsTargetPickedEmpty"));return}pe(null),Na(`script:${Ce.name}`);let z={};for(let[xe,Ve]of Object.entries(Bt))z[xe]=Ve;let se={name:Ce.name,params:z};ft==="all"?se.targets=v:ft==="selected"?se.targets=_t:se.sessionId=t;try{let xe=await ir(se);yn({result:xe&&xe.result})}catch(xe){yn({error:ne(xe)})}},Go=async(v,z)=>{let se=r.filter(xe=>(xe.folder||"")===v);for(let xe of se){let Ve=await er(xe.name),gt=sr(Ve&&Ve.script);if(!gt)throw new Error(D(e,"scriptsGetInvalid",{name:xe.name}));await tr({name:gt.name,description:gt.description,folder:z,params:gt.params,steps:gt.steps})}},Xo=()=>{let v=String(A||"").trim().slice(0,64);v!==""&&(m(z=>z.includes(v)?z:z.concat([v])),d(v),g(null),x(null),K(null),T(""),B(!1),J(D(e,"scriptsFolderAdded",{name:v})))},Jo=async()=>{let v=String(P||"").trim().slice(0,64);if(v===""||v===u){I(!1);return}Ge(!0);try{if(await Go(u,v),!Ee.current)return;hh(u,v),m(z=>z.map(se=>se===u?v:se)),I(!1),d(v),J(e("scriptsFolderRenamed")),await ai(p,{openDraft:!0,scope:v})}catch(z){J(D(e,"scriptsFolderFailed",{message:ne(z)}))}finally{Ee.current&&Ge(!1)}},Ih=async()=>{if(u){Ge(!0);try{if(await Go(u,""),!Ee.current)return;dh(u),m(v=>v.filter(z=>z!==u)),ee(!1),d(""),J(e("scriptsFolderDeleted")),await ai(p,{openDraft:!0,scope:""})}catch(v){J(D(e,"scriptsFolderFailed",{message:ne(v)}))}finally{Ee.current&&Ge(!1)}}},Xr=oi.length,Oh=()=>{if(pt)return D(e,"scriptsResultRunning",{steps:qe.length});if(qe.length===0&&!Mt)return e("scriptsProgressEmpty");let v=[D(e,"scriptsResultDone",{steps:qe.length})];return Mt&&(Mt.timedOut&&v.push(e("scriptsRunTimedOut")),v.push(D(e,"scriptsRunSummary",{runs:Mt.runs.length,ok:Mt.runs.filter(z=>z.ok).length}))),v.filter(Boolean).join(" · ")},D_=u||e("scriptsUngrouped"),A_=Ce?[Ce.description||null,D(e,"scriptsSteps",{count:Ce.stepCount}),D(e,"scriptsParamsCount",{count:Ce.paramCount})].filter(Boolean).join(" · "):"";return(0,C.jsxs)(Fi,{title:e("scriptsTitle"),onBack:i,backLabel:e("scriptsPanelClose"),children:[(0,C.jsxs)("div",{style:h.folderBar,children:[(0,C.jsx)("span",{style:h.label,children:e("scriptsFolder")}),(0,C.jsxs)("select",{style:{...h.select,flex:"1 1 120px",width:"auto"},value:u,"aria-label":e("scriptsFolderScope"),disabled:fe,onChange:v=>Yr(v.target.value),children:[(0,C.jsx)("option",{value:"",children:e("scriptsUngrouped")}),is.map(v=>(0,C.jsx)("option",{value:v,children:v},v))]}),(0,C.jsx)(Q,{style:h.rowBtnSmall,onClick:()=>{B(!0),I(!1),ee(!1)},disabled:fe,children:e("scriptsFolderAdd")}),(0,C.jsx)(Q,{style:h.rowBtnSmall,onClick:()=>{I(!0),re(u),B(!1),ee(!1)},disabled:!u||fe,children:e("scriptsFolderRename")}),(0,C.jsx)(Q,{style:h.rowBtnSmall,variant:"danger",onClick:()=>{ee(!0),I(!1),B(!1)},disabled:!u||fe,children:e("scriptsFolderDelete")})]}),E?(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("input",{style:{...h.input,width:150},value:A,"aria-label":e("scriptsFolderNew"),placeholder:e("scriptsFolderNew"),autoComplete:"off",spellCheck:!1,onChange:v=>T(v.target.value),onKeyDown:v=>{v&&v.key==="Enter"&&Xo(),v&&v.key==="Escape"&&(v.stopPropagation(),B(!1))}}),(0,C.jsx)(Q,{variant:"primary",onClick:Xo,disabled:String(A).trim()==="",children:e("scriptsFolderUse")}),(0,C.jsx)(Q,{onClick:()=>B(!1),children:e("cancel")})]}):null,w?(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("input",{style:{...h.input,width:150},value:P,"aria-label":e("scriptsFolderRename"),placeholder:e("scriptsFolderNew"),autoComplete:"off",spellCheck:!1,onChange:v=>re(v.target.value),onKeyDown:v=>{v&&v.key==="Enter"&&Jo(),v&&v.key==="Escape"&&(v.stopPropagation(),I(!1))}}),(0,C.jsx)(Q,{variant:"primary",onClick:Jo,disabled:fe,children:e("scriptsFolderUse")}),(0,C.jsx)(Q,{onClick:()=>I(!1),children:e("cancel")})]}):null,Re?(0,C.jsx)(vi,{message:D(e,"scriptsFolderDeletePrompt",{name:u}),confirmLabel:e("scriptsFolderDelete"),cancelLabel:e("cancel"),busy:fe,onConfirm:Ih,onCancel:()=>ee(!1)}):null,(0,C.jsxs)("div",{style:h.scriptSplit,children:[(0,C.jsxs)("div",{style:h.scriptListCol,children:[(0,C.jsxs)("div",{style:h.scriptListScroll,role:"listbox","aria-label":e("scriptsTitle"),children:[o==="loading"?(0,C.jsx)("div",{style:h.auditEmpty,children:e("scriptsLoading")}):null,o==="error"?(0,C.jsx)("div",{style:{...h.formError,margin:6},role:"alert",children:D(e,"scriptsListFailed",{message:c||""})}):null,o==="empty"?(0,C.jsxs)("div",{style:h.auditEmpty,children:[e("scriptsEmpty"),(0,C.jsx)("span",{style:{display:"block",fontSize:11},children:e("scriptsEmptyHint")})]}):null,o!=="loading"&&r.length>0&&zs.length===0?(0,C.jsx)("div",{style:h.auditEmpty,children:e("scriptsFolderEmpty")}):null,zs.map(v=>{let z=v.name===p;return(0,C.jsxs)("button",{type:"button",role:"option","aria-selected":z,"aria-label":v.name,title:v.description||v.name,style:{...h.listRow,...z?h.scriptRowActive:null},onClick:()=>Us(v.name),children:[(0,C.jsx)("span",{style:h.listRowTitle,children:v.name}),(0,C.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0},children:[(0,C.jsx)("span",{style:h.dialectTag,children:qr(v.name)==="macro"?e("scriptsModeMacro"):e("scriptsModeJson")}),(0,C.jsx)("span",{style:h.listRowMeta,children:D(e,"scriptsSteps",{count:v.stepCount})})]})]},v.name)})]}),(0,C.jsxs)("div",{style:{...h.scriptListButtons,position:"relative"},children:[q?(0,C.jsxs)("div",{style:h.newChoicePop,role:"menu","aria-label":e("scriptsNewType"),children:[(0,C.jsx)(Q,{style:h.newChoiceOption,onClick:()=>{W(!1),qs("macro")},disabled:le||k,children:e("scriptsModeMacro")}),(0,C.jsx)(Q,{style:h.newChoiceOption,onClick:()=>{W(!1),qs("json")},disabled:le||k,children:e("scriptsModeJson")})]}):null,(0,C.jsx)(Q,{style:h.rowBtnSmall,title:e("scriptsNewAction"),"aria-expanded":q,onClick:()=>W(v=>!v),disabled:le||k,children:`+ ${e("scriptsNewAction")}`}),(0,C.jsx)(Q,{style:h.rowBtnSmall,variant:"danger",title:e("scriptsDelete"),onClick:Le,disabled:!Ce||pt||ke,busy:ke,children:`− ${e("scriptsDelete")}`}),(0,C.jsx)(Q,{style:h.rowBtnSmall,title:e("scriptsMoveUp"),onClick:()=>Hi(-1),disabled:!$s,children:"▲"}),(0,C.jsx)(Q,{style:h.rowBtnSmall,title:e("scriptsMoveDown"),onClick:()=>Hi(1),disabled:!Ks,children:"▼"}),(0,C.jsx)(Q,{style:h.rowBtnSmall,title:e("scriptsCopy"),onClick:Ht,disabled:!Ce||le,children:e("scriptsCopy")})]})]}),(0,C.jsxs)("div",{style:h.scriptEditCol,children:[Z?(0,C.jsx)("div",{style:h.formError,role:"alert",children:Z}):null,k&&!y?(0,C.jsx)("span",{style:h.hint,children:e("scriptsLoadingEditor")}):null,y?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(Fe,{label:e("scriptsName"),hint:e("scriptsNameHint"),children:(0,C.jsx)("input",{style:h.input,value:y.meta.name,"aria-label":e("scriptsName"),autoComplete:"off",spellCheck:!1,disabled:le,onChange:v=>V({name:v.target.value})})}),(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("span",{style:h.label,children:e("scriptsFolder")}),(0,C.jsxs)("select",{style:{...h.select,flex:"1 1 110px",width:"auto"},value:y.meta.folder,"aria-label":e("scriptsFolder"),disabled:le,onChange:v=>V({folder:v.target.value}),children:[(0,C.jsx)("option",{value:"",children:e("scriptsUngrouped")}),is.map(v=>(0,C.jsx)("option",{value:v,children:v},v)),y.meta.folder&&!is.includes(y.meta.folder)?(0,C.jsx)("option",{value:y.meta.folder,children:y.meta.folder}):null]})]}),(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("span",{style:h.label,children:e("scriptsMode")}),(0,C.jsx)("span",{style:h.dialectTag,children:y.mode==="macro"?e("scriptsModeMacro"):e("scriptsModeJson")}),(0,C.jsx)("span",{style:h.hint,children:y.mode==="macro"?e("scriptsMacroHint"):e("scriptsJsonHint")})]}),y.mode==="macro"?(0,C.jsx)("span",{style:h.hint,children:e("scriptsMacroHelp")}):null,(0,C.jsxs)("div",{style:h.templateRow,children:[(0,C.jsx)("span",{style:h.label,children:e("scriptsTemplate")}),(0,C.jsxs)("select",{style:{...h.select,flex:"1 1 120px",width:"auto"},value:"","aria-label":e("scriptsTemplate"),disabled:le,onChange:v=>j(v.target.value),children:[(0,C.jsx)("option",{value:"",children:e("scriptsTemplatePlaceholder")}),(y.mode==="macro"?Uo:Ko).map(v=>(0,C.jsx)("option",{value:v.id,children:e(v.labelKey)},v.id))]})]}),(0,C.jsxs)("div",{style:{...h.field,...h.editorGrow},children:[(0,C.jsx)("span",{style:h.label,children:y.mode==="macro"?e("scriptsModeMacro"):e("scriptsSave")}),(0,C.jsx)("textarea",{style:{...h.textarea,...h.editorBody},value:y.text,spellCheck:!1,autoComplete:"off",onChange:v=>{S({text:v.target.value}),ut&&ie(!1),X&&ae(null)},disabled:le})]}),kt?(0,C.jsx)("span",{style:h.hint,children:kt}):null,X?(0,C.jsx)("div",{style:{...h.formError,whiteSpace:"pre-wrap"},role:"alert",children:X}):null,(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)(Q,{variant:"primary",onClick:_e,busy:le,disabled:le,children:e(ut?"scriptsEmptySaveConfirm":"scriptsSaveAction")}),(0,C.jsx)(Q,{onClick:Gr,disabled:le,children:e("scriptsCancel")})]})]}):k?null:(0,C.jsx)("div",{style:h.stateWrap,children:(0,C.jsx)("p",{style:h.stateDetail,children:e("scriptsEditorEmpty")})})]})]}),he?(0,C.jsx)(vi,{message:D(e,"scriptsDeletePrompt",{name:Ce?Ce.name:""}),confirmLabel:e("scriptsDeleteConfirm"),cancelLabel:e("cancel"),busy:ke,onConfirm:mt,onCancel:()=>G(!1)}):null,Ce?(0,C.jsxs)("div",{style:h.runSection,children:[(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("span",{style:h.sectionTitle,children:e("scriptsTarget")}),(0,C.jsx)(Wr,{label:e("scriptsTarget"),value:ft,disabled:pt,options:[{value:"current",label:e("scriptsTargetCurrent"),hint:e("scriptsTargetCurrent")},{value:"selected",label:e("scriptsTargetPicked"),hint:e("scriptsTargetPickedHint")},{value:"all",label:e("scriptsTargetAll"),hint:D(e,"scriptsTargetAllHint",{count:Xr})}],onChange:Ze}),(0,C.jsx)("span",{style:h.hint,children:ft==="all"?D(e,"scriptsTargetAllHint",{count:Xr}):ft==="selected"?D(e,"scriptsTargetPickedHint",{count:_t.length}):t||"—"})]}),ft==="selected"?(0,C.jsx)("div",{style:h.pickList,role:"group","aria-label":e("scriptsTargetPicked"),children:Xr===0?(0,C.jsx)("span",{style:h.hint,children:e("scriptsTargetNoSessions")}):oi.map(v=>{let z=_t.includes(v.id);return(0,C.jsxs)("label",{style:h.pickRow,children:[(0,C.jsx)("input",{type:"checkbox",checked:z,disabled:pt,onChange:()=>Wi(v.id),style:h.pickBox}),(0,C.jsx)("span",{style:h.pickTitle,children:v.title}),(0,C.jsx)("span",{style:h.pickMeta,children:__(v)})]},v.id)})}):null,Ce.paramCount>0?(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)("span",{style:h.sectionTitle,children:e("scriptsParams")}),Object.entries(Ce.params).map(([v,z])=>(0,C.jsx)(Fe,{label:v,hint:z&&z.description?z.description:void 0,children:(0,C.jsx)("input",{style:h.input,value:Bt[v]===void 0?"":Bt[v],placeholder:z&&z.default?z.default:"",autoComplete:"off",spellCheck:!1,onChange:se=>{let xe={...Bt,[v]:se.target.value};Et(xe)},onKeyDown:se=>{se&&se.key==="Enter"&&Yo()},disabled:pt})},v))]}):(0,C.jsx)("span",{style:h.hint,children:e("scriptsNoParams")}),(0,C.jsxs)("div",{style:h.actionRow,children:[(0,C.jsx)(Q,{variant:"primary",onClick:Yo,disabled:pt||!Ce,children:e(pt?"scriptsRunning":"scriptsRun")}),(0,C.jsx)("span",{style:{...h.resultSummary,flex:"1 1 140px"},children:Oh()}),(0,C.jsx)(Q,{onClick:()=>Qe(!0),title:e("scriptsResultTitle"),children:e("scriptsViewResult")})]}),$?(0,C.jsx)("div",{style:h.formError,role:"alert",children:$}):null,De.state==="done"&&!$&&De.error?(0,C.jsx)("div",{style:h.formError,role:"alert",children:D(e,"scriptsRunFailed",{message:De.error})}):null]}):null,Ue?(0,C.jsx)(Xc,{title:e("scriptsResultTitle"),closeLabel:e("scriptsResultClose"),onClose:()=>Qe(!1),children:(0,C.jsx)("div",{ref:Oe,style:h.resultBox,role:"log","aria-label":e("scriptsRun"),children:qe.length===0?(0,C.jsx)("div",{style:h.auditEmpty,children:e("scriptsProgressEmpty")}):qe.map(v=>(0,C.jsx)(g_,{line:v,t:e},v.key))})}):null]})}var L=require("react/jsx-runtime");function Bh(e){return typeof e=="function"?e:t=>t}function jo(e){return!e.sessions||e.sessions.length===0?null:e.sessions.find(i=>i.id===e.selectedId)||e.sessions[0]}function Mh({t:e,sessionId:t}){let i=Bh(e),s=zt(),r=jo(s);if((0,Ie.useEffect)(()=>{cr(t)},[t]),(0,Ie.useEffect)(()=>(Sn(),cs().catch(()=>{}),()=>Wa()),[]),(0,Ie.useEffect)(()=>{r&&s.selectedId!==r.id&&Ri(r.id)},[r?r.id:null,s.selectedId]),(0,Ie.useEffect)(()=>{if(typeof document>"u"||typeof document.addEventListener!="function")return;let c=a=>{!a||a.key!=="Escape"||a.defaultPrevented||gn()&&typeof a.preventDefault=="function"&&a.preventDefault()};return document.addEventListener("keydown",c),()=>{try{document.removeEventListener("keydown",c)}catch{}}},[]),!s.ready&&s.sessions.length===0)return(0,L.jsxs)("div",{style:h.root,children:[(0,L.jsx)("div",{style:{...h.stateWrap,flex:1},children:i("loading")}),(0,L.jsx)(Wo,{toast:s.toast})]});let n=!r&&s.view!=="connect",o=s.view==="connect"||!r,l=r&&s.resets&&s.resets[r.id]||null;return(0,L.jsxs)("div",{style:h.root,children:[(0,L.jsx)(v_,{t:i}),o?(0,L.jsx)(_h,{t:i,draft:s.connectDraft,onCancel:Ia()?()=>vn():void 0,onSaved:c=>vn(c)},s.connectDraft&&s.connectDraft.id?`edit:${s.connectDraft.id}`:"new"):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(b_,{t:i,session:r}),(0,L.jsx)(w_,{t:i,session:r,reset:l},r.id)]}),!o&&s.panel==="history"?(0,L.jsx)(vh,{t:i,sessionId:r?r.id:null,onClose:Li}):null,!o&&s.panel==="scripts"?(0,L.jsx)(Ah,{t:i,sessionId:r?r.id:null,onClose:Li}):null,n||!o&&s.panel==="profiles"?(0,L.jsx)(Sh,{t:i,onClose:n?void 0:Li}):null,(0,L.jsx)(Wo,{toast:s.toast})]})}function v_({t:e}){let t=zt(),[i,s]=(0,Ie.useState)(null),[r,n]=(0,Ie.useState)(!1),o=t.panel==="profiles",l=()=>{o?Li():lr("profiles")},c=i&&t.sessions.find(g=>g.id===i)||null,a=jo(t),u=a?a.id:null,d=new Map;for(let g of t.sessions){let y=g.title||"";d.set(y,(d.get(y)||0)+1)}let _=new Map,m=g=>{let y=g.title||"";if((d.get(y)||0)<2)return y;let x=(_.get(y)||0)+1;return _.set(y,x),`${y} #${x}`},p=async g=>{if(!r){n(!0),qi(g);try{await ge("sessions.close",{id:g})}catch(y){J(D(e,"closeFailed",{message:ne(y)}))}finally{n(!1),s(null)}}};return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)("div",{style:h.rail,role:"tablist","aria-label":e("sessions"),children:[t.sessions.map(g=>{let y=g.id===u,x=g.state==="disconnected",q=m(g);return(0,L.jsx)(y_,{t:e,session:g,label:q,active:y,disconnected:x,onSelect:()=>Ri(g.id),onRequestClose:()=>s(g.id)},g.id)}),(0,L.jsx)("span",{style:h.railSpacer}),(0,L.jsxs)(Q,{variant:o?"outline":"default",title:e("profiles"),ariaLabel:e("profiles"),onClick:l,style:{height:32,padding:"0 8px"},children:[(0,L.jsx)(sh,{}),e("profiles")]}),(0,L.jsx)("button",{type:"button",style:h.railAdd,title:e("newSession"),"aria-label":e("newSession"),onClick:()=>Vi(),children:(0,L.jsx)(Zc,{})})]}),c?(0,L.jsx)("div",{style:h.railConfirmWrap,children:(0,L.jsx)(vi,{message:D(e,"closeSessionPrompt",{title:c.title}),confirmLabel:e("closeConfirm"),cancelLabel:e("cancel"),busy:r,onConfirm:()=>p(c.id),onCancel:()=>s(null)})}):null]})}function y_({t:e,session:t,label:i,active:s,disconnected:r,onSelect:n,onRequestClose:o}){let{focus:l,focusProps:c}=Ns(),[a,u]=(0,Ie.useState)(!1),d={...h.railChip,...s?h.railChipActive:null,...!s&&a?h.railChipHover:null,...l?{boxShadow:Zi(!0)}:null};return(0,L.jsxs)("div",{role:"presentation",style:d,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),children:[(0,L.jsxs)("button",{type:"button",role:"tab","aria-selected":s,title:`${i} · ${t.username?`${t.username}@`:""}${t.host}${t.port?`:${t.port}`:""}${r?` · ${e("stateDisconnected")}`:""}`,onClick:n,style:{display:"inline-flex",alignItems:"center",gap:6,minWidth:0,height:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",fontSize:13,lineHeight:1,fontWeight:s?600:400,cursor:"pointer",outline:"none"},...c,children:[(0,L.jsx)(Gc,{state:t.state}),(0,L.jsx)("span",{style:r?h.railTitleDim:h.railTitle,children:i}),(0,L.jsx)("span",{style:{...h.transportBadge,...t.transport==="telnet"?h.transportBadgeTelnet:h.transportBadgeSsh},children:t.transport})]}),(0,L.jsx)(qt,{size:26,danger:!0,title:e("closeSession"),onClick:o,children:(0,L.jsx)(Fs,{size:12})})]})}var S_=[{value:"ro",labelKey:"permRo",hintKey:"permRoHint"},{value:"wo",labelKey:"permWo",hintKey:"permWoHint"},{value:"rw",labelKey:"permRw",hintKey:"permRwHint"}];function b_({t:e,session:t}){let s=zt().panel,r=t.permission,[n,o]=(0,Ie.useState)(()=>Date.now()),[l,c]=(0,Ie.useState)(!1),[a,u]=(0,Ie.useState)(null),[d,_]=(0,Ie.useState)(!1),[m,p]=(0,Ie.useState)(!1),[g,y]=(0,Ie.useState)(!1),x=(0,Ie.useRef)(null),q=(0,Ie.useRef)(null);(0,Ie.useEffect)(()=>{let P=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(P)},[]),(0,Ie.useEffect)(()=>{c(!1),_(!1),u(null)},[t.id]);let W=t.state==="closed"||t.state==="failed",k=t.state==="disconnected",M=k||t.state==="failed",Z=t.state==="open",K=a==="reconnect"||t.reconnecting===!0,ye=r.lockOwner,ce=ye==="ai"&&r.lockExpiresAt?Math.max(0,Math.ceil((r.lockExpiresAt-n)/1e3)):null,he=e(ye==="ai"?"lockAi":ye==="human"?"lockHuman":"lockFree"),G=ye==="ai"?f.warn:ye==="human"?f.success:f.labelTertiary,ke=async P=>{if(!a){u("access");try{let re=await ge("permission.set",{id:t.id,aiAccess:P});ds(t.id,re&&re.permission),J(e("accessChanged"))}catch(re){J(D(e,"accessFailed",{message:ne(re)}))}finally{u(null)}}},R=async()=>{if(!a){u("lock");try{let P=await ge("lock.takeOver",{id:t.id});ds(t.id,P&&P.permission),J(e("takenOver"))}catch(P){J(D(e,"takeOverFailed",{message:ne(P)}))}finally{u(null)}}},E=async()=>{if(!a){u("lock");try{let P=await ge("lock.release",{id:t.id});ds(t.id,P&&P.permission),J(e("released"))}catch(P){J(D(e,"releaseFailed",{message:ne(P)}))}finally{u(null)}}},B=async()=>{if(!m){p(!0),qi(t.id);try{await ge("sessions.close",{id:t.id})}catch(P){J(D(e,"closeFailed",{message:ne(P)}))}finally{p(!1),_(!1)}}},A=async()=>{if(!g){if(k){J(e("copyScreenUnavailable"));return}y(!0);try{let P=await ha(t.id,{changedOnly:!1}),re=ba(P);if(!re.text){J(e("copyScreenEmpty"));return}let Re=await rr(re.text,q.current);J(e(Re?"copyScreenDone":"copyFailed"))}catch(P){J(D(e,"copyScreenFailed",{message:ne(P)}))}finally{y(!1)}}},T=async()=>{if(!(a||!Z)){u("disconnect");try{let P=await sa(t.id);P&&P.session&&$t(P.session),J(e("disconnectedNotice"))}catch(P){J(D(e,"disconnectFailed",{message:ne(P)}))}finally{u(null)}}},w=async()=>{if(!a){u("reconnect");try{let P=Ma(t.id)||{cols:t.cols,rows:t.rows},re=await ra(t.id,P),Re=re&&re.session?$t(re.session):null;Re&&Re.state==="failed"?J(D(e,"reconnectFailed",{message:Re.error||e("unknownError")})):Re&&Re.state==="open"&&J(e("reconnected"))}catch(P){J(D(e,"reconnectFailed",{message:ne(P)}))}finally{u(null)}}},I=P=>{s===P?Li():lr(P)};return(0,L.jsxs)(L.Fragment,{children:[(0,L.jsxs)("div",{ref:q,style:{...h.controlBar,position:"relative"},children:[(0,L.jsx)(Wr,{label:e("permission"),value:r.aiAccess,disabled:W||a!==null,options:S_.map(P=>({value:P.value,label:e(P.labelKey),hint:e(P.hintKey)})),onChange:ke}),(0,L.jsxs)("span",{style:{...h.lockChip,color:G},title:`${e("lockFree")} / ${e("lockAi")} / ${e("lockHuman")}`,children:[ye?(0,L.jsx)($o,{}):(0,L.jsx)("span",{style:{...h.lockDot,background:G}}),(0,L.jsx)("span",{children:he}),ce!==null?(0,L.jsxs)("span",{style:{color:f.labelTertiary},children:["· ",D(e,"lockAiCountdown",{seconds:ce})]}):null]}),(0,L.jsx)("div",{style:h.controlSpacer}),M?(0,L.jsxs)(Q,{title:e("reconnectAction"),ariaLabel:e(K?"reconnectingAction":"reconnectAction"),onClick:w,busy:K,disabled:a!==null,children:[(0,L.jsx)(oh,{size:14}),e("reconnectAction")]}):ye==="human"?(0,L.jsx)(Q,{onClick:E,disabled:a!==null,children:e("releaseAi")}):(0,L.jsx)(Q,{onClick:R,disabled:a!==null||W,children:e("takeOver")}),Z?(0,L.jsx)(qt,{danger:!0,title:e("disconnect"),ariaLabel:e("disconnectHint"),disabled:a!==null||t.reconnecting===!0,onClick:T,children:a==="disconnect"?(0,L.jsx)("span",{style:{fontSize:12},children:"…"}):(0,L.jsx)(nh,{})}):null,(0,L.jsx)(qt,{active:s==="history",title:e("history"),onClick:()=>I("history"),children:(0,L.jsx)(th,{})}),(0,L.jsx)(qt,{active:s==="scripts",title:e("scripts"),onClick:()=>I("scripts"),children:(0,L.jsx)(ih,{})}),(0,L.jsx)(qt,{title:e(k?"copyScreenUnavailable":"copyScreen"),disabled:g||k,onClick:A,children:g?(0,L.jsx)("span",{style:{fontSize:12},children:"…"}):(0,L.jsx)(rh,{})}),(0,L.jsxs)("div",{ref:x,style:{position:"relative",display:"inline-flex",flex:"none"},children:[(0,L.jsxs)(qt,{active:l,title:e("audit"),onClick:()=>c(P=>!P),children:[(0,L.jsx)(Qc,{}),(0,L.jsx)(eh,{open:l})]}),(0,L.jsx)(mh,{t:e,sessionId:t.id,open:l,onClose:()=>c(!1),rootRef:x})]}),(0,L.jsx)(qt,{danger:!0,title:e("closeSession"),onClick:()=>_(!0),children:(0,L.jsx)(Fs,{})})]}),d?(0,L.jsx)("div",{style:h.railConfirmWrap,children:(0,L.jsx)(vi,{message:D(e,"closeSessionPrompt",{title:t.title}),confirmLabel:e("closeConfirm"),cancelLabel:e("cancel"),busy:m,onConfirm:B,onCancel:()=>_(!1)})}):null]})}function w_({t:e,session:t,reset:i}){let[s,r]=(0,Ie.useState)("connecting"),[n,o]=(0,Ie.useState)(!1),l=!!t.permission.humanWriteBlocked,c=t.state==="closed"||t.state==="failed",a=t.state==="disconnected";return(0,L.jsxs)("div",{style:h.pane,children:[l&&!c&&!a?(0,L.jsx)(x_,{t:e,session:t}):null,a?(0,L.jsx)(C_,{t:e,session:t}):null,c?(0,L.jsx)(k_,{t:e,session:t}):null,(0,L.jsx)("div",{style:h.termWrap,children:(0,L.jsx)(Yc,{t:e,session:t,onLinkChange:r,reset:i})}),(0,L.jsx)(fh,{t:e,sessionId:c||a?null:t.id,open:n,onToggle:()=>o(u=>!u),onOpenLibrary:()=>lr("scripts")}),(0,L.jsx)(E_,{t:e,session:t,link:s})]})}function C_({t:e,session:t}){return(0,L.jsx)("div",{style:{...h.banner,borderLeftColor:f.warn},role:"status",children:(0,L.jsxs)("span",{style:h.bannerText,children:[e("disconnectedTitle"),(0,L.jsx)("span",{style:h.bannerHint,children:e("disconnectedHint")}),t.closeReason?(0,L.jsx)("span",{style:h.bannerHint,children:D(e,"closedReason",{reason:t.closeReason})}):null]})})}function x_({t:e,session:t}){let[i,s]=(0,Ie.useState)(!1),r=async()=>{if(!i){s(!0);try{let n=await ge("lock.takeOver",{id:t.id});ds(t.id,n&&n.permission),J(e("takenOver"))}catch(n){J(D(e,"takeOverFailed",{message:ne(n)}))}finally{s(!1)}}};return(0,L.jsxs)("div",{style:h.banner,role:"status",children:[(0,L.jsx)($o,{size:12}),(0,L.jsxs)("span",{style:h.bannerText,children:[e("blockedTitle"),(0,L.jsx)("span",{style:h.bannerHint,children:e("blockedHint")})]}),(0,L.jsx)(Q,{variant:"primary",onClick:r,busy:i,disabled:i,children:e("takeOver")})]})}function k_({t:e,session:t}){let i=t.state==="failed",[s,r]=(0,Ie.useState)(!1),n=async()=>{if(!s){r(!0);try{await ge("sessions.close",{id:t.id})}catch{}finally{r(!1),qi(t.id,t.error)}}};return(0,L.jsxs)("div",{style:{...h.banner,borderLeftColor:i?f.danger:f.labelTertiary},role:"status",children:[(0,L.jsxs)("span",{style:h.bannerText,children:[e(i?"failedTitle":"closedTitle"),t.error?(0,L.jsx)("span",{style:h.bannerHint,children:D(e,"closedReason",{reason:t.error})}):null]}),(0,L.jsx)(Q,{onClick:n,busy:s,disabled:s,children:e("closeSession")})]})}function E_({t:e,session:t,link:i}){let s=t.state==="open"?"stateOpen":t.state==="disconnected"?"stateDisconnected":t.state==="closed"?"stateClosed":t.state==="failed"?"stateFailed":"stateConnecting",r=t.reconnecting===!0||t.state==="open"&&i==="error",n=t.state==="failed"?f.danger:r||t.state==="disconnected"?f.warnLabel:f.labelTertiary,o=`${t.transport==="telnet"?"telnet":"ssh"} ${t.username?`${t.username}@`:""}${t.host}${t.port?`:${t.port}`:""}`;return(0,L.jsxs)("div",{style:h.statusBar,children:[(0,L.jsx)("span",{style:{...h.statusItem,color:n},children:e(r?"reconnecting":s)}),(0,L.jsx)("span",{style:h.statusItem,children:o}),(0,L.jsx)("span",{style:h.controlSpacer}),(0,L.jsx)("span",{style:h.statusItem,children:D(e,"statusSize",{cols:t.cols,rows:t.rows})}),(0,L.jsx)("span",{style:h.statusItem,children:D(e,"statusBytes",{in:Ei(t.bytesIn),out:Ei(t.bytesOut)})})]})}function Ph({t:e}){let t=Bh(e),i=zt(),s=jo(i);return(0,L.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,minWidth:0,maxWidth:220},children:[(0,L.jsx)(Jc,{size:12}),s?(0,L.jsx)("span",{style:{...h.transportBadge,...s.transport==="telnet"?h.transportBadgeTelnet:h.transportBadgeSsh},children:s.transport}):null,(0,L.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s?s.title:t("title")})]})}var Vr="dsh-aiterm",jr="aiterm",R_=["slots","locale","sidebarRight","sidebarRightTabs"];function L_(e){let t=e.locale.bind(ns);e.effect(()=>e.locale.register(ns,{zh:Zo,en:Qo}),"aiterm: locale"),e.effect(()=>e.sidebarRightTabs.register({id:Vr,kind:jr,multiple:!1,priority:"extension",title:()=>t("title"),guide:[{id:"open",order:30,title:()=>t("title"),description:()=>t("guide")}]}),"aiterm: tab type");for(let i of[Vr,jr])e.effect(()=>e.slots.inject("sidebar.right.pane.tab",()=>e.slots.register({name:"sidebar.right.pane.tab",key:i,locale:ns,inject:s=>({sessionId:s})},Mh)),`aiterm: pane body (${i})`),e.effect(()=>e.slots.inject("sidebar.right.pane.tab.title",()=>e.slots.register({name:"sidebar.right.pane.tab.title",key:i,locale:ns,inject:s=>({sessionId:s})},Ph)),`aiterm: pane title (${i})`);try{globalThis.__DSH_AITERM_CLIENT__={plugin:Vr,kind:jr,route:"/aiterm",version:"0.5.12",internals:{applyReset:Hr,createResetTracker:Fr,resetNotice:No,buildReconnectPayload:en,getState:or,setOwner:cr}}}catch{}}
|
|
397
397
|
|
|
398
398
|
return module.exports;
|
|
399
399
|
},
|