@andy.ian/dsh-homing 2.0.1 → 2.0.3
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/bin/watchdog.mjs +99 -118
- package/index.js +55 -211
- package/lib/files-page.mjs +12 -113
- package/package.json +2 -4
- package/client.js +0 -79
- package/lib/session.mjs +0 -216
- package/lib/shell-page.mjs +0 -430
- package/lib/shell.mjs +0 -274
- package/ops/watchdog/dsh-watchdog.ps1 +0 -105
- package/ops/watchdog/restart-hidden.vbs +0 -7
- package/ops/watchdog/restart-now.ps1 +0 -261
- package/ops/watchdog/run-hidden.vbs +0 -4
package/lib/session.mjs
DELETED
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 常驻 shell 会话:让手机终端像真 bash 一样保留状态(cwd / 环境变量 / 函数)。
|
|
3
|
-
*
|
|
4
|
-
* 关键设计(踩过的坑写在这里):
|
|
5
|
-
* 1. 不用 PTY:Git Bash 自带的 winpty 在无控制台进程里断言失败;真 PTY 要 ConPTY + 原生模块。
|
|
6
|
-
* 2. 一个 bash 进程从 stdin 顺序读命令,命令前后打标记,一次往返拿到「输出 + 退出码 + $PWD」。
|
|
7
|
-
* 3. **子进程退出回调必须校验"我还当权吗"**:
|
|
8
|
-
* 旧进程的 exit 事件是异步投递的,若回调无条件把 this.child 置空,
|
|
9
|
-
* 会把刚重启的新进程引用清掉,导致"永远显示会话已退出"的假死循环。
|
|
10
|
-
*/
|
|
11
|
-
import { spawn } from 'node:child_process'
|
|
12
|
-
import { findBash } from './shell.mjs'
|
|
13
|
-
|
|
14
|
-
/** Git Bash 的 /d/x 转回 D:\\x(Git Bash 也认 D:/x,所以转换后可直接 cd) */
|
|
15
|
-
function toWindowsPath(value) {
|
|
16
|
-
const text = String(value ?? '').trim()
|
|
17
|
-
// pwd -W 给的是 C:/Users/... 形式,统一成反斜杠,和 path.resolve 比较时不打架
|
|
18
|
-
if (/^[A-Za-z]:[\\/]/u.test(text)) return text.replaceAll('/', '\\')
|
|
19
|
-
const match = /^\/([A-Za-z])(?:\/(.*))?$/u.exec(text)
|
|
20
|
-
if (match === null) return text
|
|
21
|
-
const drive = match[1].toUpperCase()
|
|
22
|
-
const rest = (match[2] ?? '').replaceAll('/', '\\')
|
|
23
|
-
return rest === '' ? drive + ':\\' : drive + ':\\' + rest
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const MAX_OUTPUT = 64 * 1024
|
|
27
|
-
const DEFAULT_TIMEOUT = 30_000
|
|
28
|
-
|
|
29
|
-
export class ShellSession {
|
|
30
|
-
constructor(cwd) {
|
|
31
|
-
// spawn 必须用 Windows 路径;bash 的 $PWD(/d/xxx)只用于显示
|
|
32
|
-
this.winCwd = cwd
|
|
33
|
-
this.cwd = cwd
|
|
34
|
-
this.child = null
|
|
35
|
-
this.queue = Promise.resolve()
|
|
36
|
-
this.startedAt = 0
|
|
37
|
-
this.commandCount = 0
|
|
38
|
-
this.buffer = ''
|
|
39
|
-
// 终端页的滚动记录(最近 100 条),页面刷新后还能看到上下文
|
|
40
|
-
this.transcript = []
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
get running() {
|
|
44
|
-
const child = this.child
|
|
45
|
-
return child !== null && child.exitCode === null && !child.killed
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
start() {
|
|
49
|
-
const bash = findBash()
|
|
50
|
-
if (bash === null) throw new Error('找不到 Git Bash')
|
|
51
|
-
const child = spawn(bash, ['--noprofile', '--norc'], {
|
|
52
|
-
cwd: this.winCwd,
|
|
53
|
-
env: {
|
|
54
|
-
...process.env,
|
|
55
|
-
TERM: 'dumb',
|
|
56
|
-
PAGER: 'cat',
|
|
57
|
-
GIT_PAGER: 'cat',
|
|
58
|
-
GIT_TERMINAL_PROMPT: '0',
|
|
59
|
-
LANG: 'C.UTF-8',
|
|
60
|
-
},
|
|
61
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
62
|
-
windowsHide: true,
|
|
63
|
-
})
|
|
64
|
-
this.child = child
|
|
65
|
-
this.buffer = ''
|
|
66
|
-
this.startedAt = Date.now()
|
|
67
|
-
this.commandCount = 0
|
|
68
|
-
|
|
69
|
-
child.stdout.on('data', (chunk) => { this.buffer += chunk.toString('utf8') })
|
|
70
|
-
child.stderr.on('data', (chunk) => { this.buffer += chunk.toString('utf8') })
|
|
71
|
-
// 只清理"自己这一代"的引用:否则旧进程的退出事件会把新进程清掉
|
|
72
|
-
const clearIfCurrent = () => {
|
|
73
|
-
if (this.child === child) this.child = null
|
|
74
|
-
}
|
|
75
|
-
child.on('error', clearIfCurrent)
|
|
76
|
-
child.on('exit', clearIfCurrent)
|
|
77
|
-
return this
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
record(entry) {
|
|
81
|
-
this.transcript.push(entry)
|
|
82
|
-
if (this.transcript.length > 100) this.transcript.shift()
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* 中断当前命令(相当于 Ctrl+C)。
|
|
87
|
-
*
|
|
88
|
-
* 注意:bash 的 stdin 是管道而不是终端,写 \x03 不会产生 SIGINT信号,
|
|
89
|
-
* 所以这里直接杀掉 bash 进程(连同它启动的子进程树),再起一个新的。
|
|
90
|
-
* 代价是 cwd / 环境变量会被重置 —— 这和"卡死的命令必须停下来"相比是值得的。
|
|
91
|
-
*/
|
|
92
|
-
interrupt() {
|
|
93
|
-
this.reset()
|
|
94
|
-
return { ok: true, code: null, output: '(已中断,会话已重启)', cwd: this.winCwd }
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
reset() {
|
|
98
|
-
this.kill()
|
|
99
|
-
this.start()
|
|
100
|
-
return this
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
kill() {
|
|
104
|
-
const child = this.child
|
|
105
|
-
this.child = null
|
|
106
|
-
try {
|
|
107
|
-
child?.kill()
|
|
108
|
-
} catch {
|
|
109
|
-
// 已退出
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** 串行执行(同一个 shell 不能并发写 stdin) */
|
|
114
|
-
run(command) {
|
|
115
|
-
const job = () => this.#runOnce(command)
|
|
116
|
-
this.queue = this.queue.then(job, job)
|
|
117
|
-
return this.queue
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
#runOnce(command) {
|
|
121
|
-
const text = String(command ?? '').trim()
|
|
122
|
-
if (text === '') return Promise.resolve({ ok: false, error: '命令为空', cwd: this.cwd })
|
|
123
|
-
|
|
124
|
-
// exit 会真的结束 shell:直接当作"重置会话",并如实返回退出码
|
|
125
|
-
const exitMatch = /^exit(?:\s+(\d+))?\s*$/u.exec(text)
|
|
126
|
-
if (exitMatch !== null) {
|
|
127
|
-
const code = exitMatch[1] === undefined ? 0 : Number(exitMatch[1])
|
|
128
|
-
this.reset()
|
|
129
|
-
return Promise.resolve({
|
|
130
|
-
ok: code === 0,
|
|
131
|
-
code,
|
|
132
|
-
output: '(会话已重启:环境变量清空,当前目录保持)',
|
|
133
|
-
cwd: this.cwd,
|
|
134
|
-
})
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
if (!this.running) this.start()
|
|
138
|
-
|
|
139
|
-
const id = `m${Math.random().toString(36).slice(2, 10)}`
|
|
140
|
-
const startTag = `<<${id}S>>`
|
|
141
|
-
const endTag = `<<${id}E:`
|
|
142
|
-
this.buffer = ''
|
|
143
|
-
this.child.stdin.write(`printf '${startTag}\\n'\n${text}\nprintf '${endTag}%s|%s>>\\n' "$?" "$(pwd -W 2>/dev/null || pwd)"\n`)
|
|
144
|
-
this.commandCount += 1
|
|
145
|
-
|
|
146
|
-
const started = Date.now()
|
|
147
|
-
return new Promise((resolve) => {
|
|
148
|
-
const timer = setInterval(() => {
|
|
149
|
-
const endIndex = this.buffer.indexOf(endTag)
|
|
150
|
-
if (endIndex >= 0) {
|
|
151
|
-
clearInterval(timer)
|
|
152
|
-
const after = this.buffer.slice(endIndex + endTag.length)
|
|
153
|
-
const closeIndex = after.indexOf('>>')
|
|
154
|
-
if (closeIndex < 0) return
|
|
155
|
-
const [codeText, cwdText] = after.slice(0, closeIndex).split('|')
|
|
156
|
-
const startIndex = this.buffer.indexOf(startTag)
|
|
157
|
-
const output = startIndex >= 0
|
|
158
|
-
? this.buffer.slice(startIndex + startTag.length, endIndex).replace(/^\r?\n/u, '')
|
|
159
|
-
: this.buffer.slice(0, endIndex)
|
|
160
|
-
if (cwdText) {
|
|
161
|
-
this.cwd = cwdText
|
|
162
|
-
this.winCwd = toWindowsPath(cwdText)
|
|
163
|
-
}
|
|
164
|
-
const code = Number(codeText)
|
|
165
|
-
resolve({
|
|
166
|
-
ok: code === 0,
|
|
167
|
-
code,
|
|
168
|
-
output: output.length > MAX_OUTPUT
|
|
169
|
-
? output.slice(0, MAX_OUTPUT)
|
|
170
|
-
: (output.trim() === '' ? '(无输出)' : output),
|
|
171
|
-
cwd: this.winCwd,
|
|
172
|
-
bashCwd: this.cwd,
|
|
173
|
-
truncated: output.length > MAX_OUTPUT,
|
|
174
|
-
})
|
|
175
|
-
return
|
|
176
|
-
}
|
|
177
|
-
if (Date.now() - started > DEFAULT_TIMEOUT) {
|
|
178
|
-
clearInterval(timer)
|
|
179
|
-
this.kill()
|
|
180
|
-
resolve({
|
|
181
|
-
ok: false,
|
|
182
|
-
code: null,
|
|
183
|
-
timeout: true,
|
|
184
|
-
output: this.buffer.slice(0, 2000) + '\n(超时 30 秒,会话已重启)',
|
|
185
|
-
cwd: this.winCwd,
|
|
186
|
-
})
|
|
187
|
-
}
|
|
188
|
-
}, 30)
|
|
189
|
-
})
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
info() {
|
|
193
|
-
return {
|
|
194
|
-
running: this.running,
|
|
195
|
-
cwd: this.winCwd,
|
|
196
|
-
bashCwd: this.cwd,
|
|
197
|
-
commands: this.commandCount,
|
|
198
|
-
transcript: this.transcript.slice(-100),
|
|
199
|
-
uptimeMs: this.startedAt === 0 ? 0 : Date.now() - this.startedAt,
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
let shared = null
|
|
205
|
-
|
|
206
|
-
export function sharedSession(cwd) {
|
|
207
|
-
if (shared === null || !shared.running) {
|
|
208
|
-
shared = new ShellSession(cwd)
|
|
209
|
-
shared.start()
|
|
210
|
-
}
|
|
211
|
-
return shared
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
export function resetSharedSession() {
|
|
215
|
-
if (shared !== null) shared.reset()
|
|
216
|
-
}
|
package/lib/shell-page.mjs
DELETED
|
@@ -1,430 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* /shell 终端页:模仿 Git Bash(mintty)的样子。
|
|
3
|
-
*
|
|
4
|
-
* 提示符是两行(和 mintty 一致):
|
|
5
|
-
* andyi@DESKTOP-JH8H48I MINGW64 /c/Users/.../workspace (main)
|
|
6
|
-
* $ ▮
|
|
7
|
-
* 第一行是信息行(用户名@主机 / MINGW64 / MSYS 风格路径 / 当前分支),
|
|
8
|
-
* 第二行只有一个 $ 和正在输入的命令(textarea,长命令自动换行增高)。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const escapeHtml = (value) => String(value ?? '')
|
|
12
|
-
.replaceAll('&', '&')
|
|
13
|
-
.replaceAll('<', '<')
|
|
14
|
-
.replaceAll('>', '>')
|
|
15
|
-
.replaceAll('"', '"')
|
|
16
|
-
.replaceAll("'", ''')
|
|
17
|
-
|
|
18
|
-
/** C:\Users\x → /c/Users/x(mintty 里显示的样子) */
|
|
19
|
-
export const toMsys = (value) => {
|
|
20
|
-
const text = String(value ?? '')
|
|
21
|
-
const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(text)
|
|
22
|
-
if (match === null) return text
|
|
23
|
-
const rest = match[2].replaceAll('\\', '/').replace(/\/+$/u, '')
|
|
24
|
-
return '/' + match[1].toLowerCase() + (rest === '' ? '' : '/' + rest)
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const STYLE = `
|
|
28
|
-
:root { color-scheme: dark; }
|
|
29
|
-
* { box-sizing: border-box; }
|
|
30
|
-
html, body { height: 100%; }
|
|
31
|
-
body {
|
|
32
|
-
margin: 0; background: #0c0c0c; color: #cccccc;
|
|
33
|
-
font-family: "Cascadia Mono", Consolas, "DejaVu Sans Mono", "Noto Sans Mono CJK SC", monospace;
|
|
34
|
-
font-size: 13px; display: flex; flex-direction: column;
|
|
35
|
-
}
|
|
36
|
-
.top {
|
|
37
|
-
display: flex; gap: 8px; align-items: center; padding: 6px 10px;
|
|
38
|
-
background: #1c1c1c; border-bottom: 1px solid #2a2a2a; font-size: 12px; color: #9a9a9a;
|
|
39
|
-
flex: 0 0 auto;
|
|
40
|
-
}
|
|
41
|
-
.top a { color: #6cb6ff; text-decoration: none; }
|
|
42
|
-
.top .spacer { flex: 1; }
|
|
43
|
-
#term {
|
|
44
|
-
flex: 1 1 auto; overflow-y: auto; padding: 8px 10px 12px;
|
|
45
|
-
white-space: normal; word-break: break-word; line-height: 1.45;
|
|
46
|
-
}
|
|
47
|
-
.ps1line { color: #cccccc; margin: 6px 0 0; white-space: normal; }
|
|
48
|
-
.ps1line .user { color: #6ad46a; }
|
|
49
|
-
.ps1line .mingw { color: #e6c07b; }
|
|
50
|
-
.ps1line .path { color: #e6c07b; word-break: break-all; }
|
|
51
|
-
.ps1line .branch { color: #56c8d8; }
|
|
52
|
-
.cmdline { color: #ffffff; white-space: pre-wrap; }
|
|
53
|
-
.cmdline .dollar { color: #ffffff; }
|
|
54
|
-
.out { margin: 0 0 2px; color: #cccccc; }
|
|
55
|
-
.err { color: #ff8f8f; }
|
|
56
|
-
.meta { color: #7a7a7a; font-size: 11px; margin-bottom: 2px; }
|
|
57
|
-
form.input { display: flex; gap: 6px; align-items: flex-start; margin: 0; padding: 0; }
|
|
58
|
-
form.input .dollar { flex: 0 0 auto; color: #ffffff; }
|
|
59
|
-
#cmd {
|
|
60
|
-
flex: 1 1 0; min-width: 80px; background: transparent; border: 0; outline: 0;
|
|
61
|
-
color: #ffffff; font: inherit; font-size: 13px; line-height: 1.45;
|
|
62
|
-
caret-color: #ffffff; resize: none; overflow: hidden; padding: 0;
|
|
63
|
-
white-space: pre-wrap; word-break: break-word; min-height: 1.5em;
|
|
64
|
-
}
|
|
65
|
-
form.input .tools { display: flex; gap: 6px; flex: 0 0 auto; }
|
|
66
|
-
button {
|
|
67
|
-
flex: 0 0 auto; padding: 6px 10px; border-radius: 6px; border: 1px solid #333;
|
|
68
|
-
background: #232323; color: #cfcfcf; font: inherit; font-size: 12px;
|
|
69
|
-
}
|
|
70
|
-
button.primary { background: #2d5bd7; border-color: #2d5bd7; color: #fff; }
|
|
71
|
-
.toolbar { display: flex; gap: 6px; padding-top: 6px; }
|
|
72
|
-
.toolbar button { min-width: 44px; text-align: center; }
|
|
73
|
-
.toolbar button.toggle { min-width: 56px; }
|
|
74
|
-
/* Ctrl 按下态:和高亮一致,松开即恢复 */
|
|
75
|
-
button.pressed {
|
|
76
|
-
background: #2d5bd7; border-color: #2d5bd7; color: #fff;
|
|
77
|
-
box-shadow: 0 0 0 1px #2d5bd7 inset;
|
|
78
|
-
}
|
|
79
|
-
.hint { color: #7a7a7a; font-size: 11px; padding-top: 4px; }
|
|
80
|
-
#cands { display: flex; flex-wrap: wrap; gap: 6px; padding-top: 6px; }
|
|
81
|
-
#cands button { background: #1b2030; border: 1px solid #2a3550; color: #9fc0ff; font-size: 12px; padding: 5px 9px; border-radius: 999px; }
|
|
82
|
-
`
|
|
83
|
-
|
|
84
|
-
/** 信息行:user@host MINGW64 /c/path (branch) */
|
|
85
|
-
export const promptInfo = ({ cwd = '', user = '', host = '', branch = '' } = {}) => {
|
|
86
|
-
const head = user === '' ? '' : `<span class="user">${escapeHtml(user)}${host === '' ? '' : '@' + escapeHtml(host)}</span> `
|
|
87
|
-
const mingw = '<span class="mingw">MINGW64</span> '
|
|
88
|
-
const path = `<span class="path">${escapeHtml(toMsys(cwd))}</span>`
|
|
89
|
-
const br = branch === '' ? '' : ` <span class="branch">(${escapeHtml(branch)})</span>`
|
|
90
|
-
return `<div class="ps1line">${head}${mingw}${path}${br}</div>`
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function renderShellPage({
|
|
94
|
-
cwd = '',
|
|
95
|
-
transcript = [],
|
|
96
|
-
running = true,
|
|
97
|
-
user = '',
|
|
98
|
-
host = '',
|
|
99
|
-
branch = '',
|
|
100
|
-
}) {
|
|
101
|
-
const infoHtml = (dir, br) => promptInfo({ cwd: dir || cwd, user, host, branch: br ?? branch })
|
|
102
|
-
const entries = transcript.map((entry) => [
|
|
103
|
-
infoHtml(entry.cwd || cwd, entry.branch),
|
|
104
|
-
`<div class="cmdline"><span class="dollar">$</span> ${escapeHtml(entry.command)}</div>`,
|
|
105
|
-
entry.output === undefined
|
|
106
|
-
? ''
|
|
107
|
-
: `<div class="${entry.ok === false && entry.code !== 0 ? 'out err' : 'out'}">${escapeHtml(entry.output)}</div>`,
|
|
108
|
-
].join('')).join('')
|
|
109
|
-
|
|
110
|
-
const body = `
|
|
111
|
-
<div class="top">
|
|
112
|
-
<a href="/files?path=${encodeURIComponent(cwd)}">文件</a>
|
|
113
|
-
<a href="/git?path=${encodeURIComponent(cwd)}">Git</a>
|
|
114
|
-
<span class="spacer"></span>
|
|
115
|
-
<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:52%">${escapeHtml(toMsys(cwd))}</span>
|
|
116
|
-
<button id="reset" type="button">重置</button>
|
|
117
|
-
</div>
|
|
118
|
-
<div id="term">${entries || '<div class="meta">这是你电脑上的 Git Bash,输入命令后回车执行</div>'}
|
|
119
|
-
<div id="ps1meta">${infoHtml(cwd)}</div>
|
|
120
|
-
<form class="input" id="term-form">
|
|
121
|
-
<span class="dollar">$</span>
|
|
122
|
-
<textarea id="cmd" name="command" rows="1" autocomplete="off" autocapitalize="off" autocorrect="off"
|
|
123
|
-
spellcheck="false" autofocus></textarea>
|
|
124
|
-
<span class="tools">
|
|
125
|
-
<button type="submit" class="primary">执行</button>
|
|
126
|
-
</span>
|
|
127
|
-
</form>
|
|
128
|
-
<div class="toolbar">
|
|
129
|
-
<button type="button" id="histUp" title="上一条历史命令">↑</button>
|
|
130
|
-
<button type="button" id="histDown" title="下一条历史命令">↓</button>
|
|
131
|
-
<button type="button" id="ctrlkey" class="toggle" aria-pressed="false"
|
|
132
|
-
title="Ctrl:按下后按字母触发 Ctrl 组合键">Ctrl</button>
|
|
133
|
-
<button type="button" id="tabkey" title="补全">Tab</button>
|
|
134
|
-
</div>
|
|
135
|
-
<div id="cands"></div>
|
|
136
|
-
<div class="hint" id="ctrlhint"></div>
|
|
137
|
-
</div>
|
|
138
|
-
<script>
|
|
139
|
-
(function () {
|
|
140
|
-
var term = document.getElementById('term');
|
|
141
|
-
var form = document.getElementById('term-form');
|
|
142
|
-
var input = document.getElementById('cmd');
|
|
143
|
-
var cands = document.getElementById('cands');
|
|
144
|
-
var meta = document.getElementById('ps1meta');
|
|
145
|
-
var currentCwd = ${JSON.stringify(cwd)};
|
|
146
|
-
var currentBranch = ${JSON.stringify(branch)};
|
|
147
|
-
var userName = ${JSON.stringify(user)};
|
|
148
|
-
var hostName = ${JSON.stringify(host)};
|
|
149
|
-
|
|
150
|
-
function esc(text) {
|
|
151
|
-
return String(text == null ? '' : text)
|
|
152
|
-
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
153
|
-
}
|
|
154
|
-
function toMsys(value) {
|
|
155
|
-
var m = String(value || '').match(/^([A-Za-z]):[\\\\/]?(.*)$/);
|
|
156
|
-
if (!m) return String(value || '');
|
|
157
|
-
var rest = m[2].replace(/\\\\/g, '/').replace(/\\/+$/, '');
|
|
158
|
-
return '/' + m[1].toLowerCase() + (rest === '' ? '' : '/' + rest);
|
|
159
|
-
}
|
|
160
|
-
function infoHtml() {
|
|
161
|
-
var head = userName === '' ? '' : '<span class="user">' + esc(userName) + (hostName === '' ? '' : '@' + esc(hostName)) + '</span> ';
|
|
162
|
-
var br = currentBranch === '' ? '' : ' <span class="branch">(' + esc(currentBranch) + ')</span>';
|
|
163
|
-
return '<div class="ps1line">' + head + '<span class="mingw">MINGW64</span> <span class="path">' + esc(toMsys(currentCwd)) + '</span>' + br + '</div>';
|
|
164
|
-
}
|
|
165
|
-
function scrollBottom() { term.scrollTop = term.scrollHeight; }
|
|
166
|
-
function autosize() {
|
|
167
|
-
input.style.height = 'auto';
|
|
168
|
-
input.style.height = Math.min(input.scrollHeight, Math.round(window.innerHeight * 0.4)) + 'px';
|
|
169
|
-
scrollBottom();
|
|
170
|
-
}
|
|
171
|
-
function renderCands(items) {
|
|
172
|
-
cands.innerHTML = '';
|
|
173
|
-
(items || []).slice(0, 12).forEach(function (item) {
|
|
174
|
-
var b = document.createElement('button');
|
|
175
|
-
b.type = 'button';
|
|
176
|
-
b.textContent = item.label;
|
|
177
|
-
b.addEventListener('click', function () { insert(item.value); });
|
|
178
|
-
cands.appendChild(b);
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
-
function insert(value) {
|
|
182
|
-
var text = input.value;
|
|
183
|
-
var m = text.match(/(\\S+)$/);
|
|
184
|
-
input.value = (m ? text.slice(0, m.index) : text) + value;
|
|
185
|
-
input.focus();
|
|
186
|
-
autosize();
|
|
187
|
-
fetchComplete();
|
|
188
|
-
}
|
|
189
|
-
function fetchComplete() {
|
|
190
|
-
var lineText = input.value;
|
|
191
|
-
if (lineText.trim() === '') { cands.innerHTML = ''; return; }
|
|
192
|
-
fetch('/shell/complete?cwd=' + encodeURIComponent(currentCwd) + '&line=' + encodeURIComponent(lineText))
|
|
193
|
-
.then(function (r) { return r.ok ? r.json() : []; })
|
|
194
|
-
.then(renderCands)
|
|
195
|
-
.catch(function () {});
|
|
196
|
-
}
|
|
197
|
-
function completeNow() {
|
|
198
|
-
var lineText = input.value;
|
|
199
|
-
if (lineText.trim() === '') return;
|
|
200
|
-
fetch('/shell/complete?cwd=' + encodeURIComponent(currentCwd) + '&line=' + encodeURIComponent(lineText))
|
|
201
|
-
.then(function (r) { return r.ok ? r.json() : []; })
|
|
202
|
-
.then(function (items) {
|
|
203
|
-
if (!items || items.length === 0) { renderCands([]); return; }
|
|
204
|
-
renderCands(items);
|
|
205
|
-
if (items.length === 1) { insert(items[0].value); return; }
|
|
206
|
-
var prefix = items[0].value;
|
|
207
|
-
for (var i = 1; i < items.length; i += 1) {
|
|
208
|
-
while (prefix.length > 0 && items[i].value.indexOf(prefix) !== 0) prefix = prefix.slice(0, -1);
|
|
209
|
-
}
|
|
210
|
-
if (prefix.length > 0) insert(prefix);
|
|
211
|
-
})
|
|
212
|
-
.catch(function () {});
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
form.addEventListener('submit', function (event) {
|
|
216
|
-
event.preventDefault();
|
|
217
|
-
var command = input.value;
|
|
218
|
-
if (command.trim() === '') return;
|
|
219
|
-
rememberHistory(command);
|
|
220
|
-
input.value = '';
|
|
221
|
-
autosize();
|
|
222
|
-
cands.innerHTML = '';
|
|
223
|
-
|
|
224
|
-
var block = document.createElement('div');
|
|
225
|
-
block.innerHTML = infoHtml() + '<div class="cmdline"><span class="dollar">$</span> ' + esc(command) + '</div>';
|
|
226
|
-
term.insertBefore(block, meta);
|
|
227
|
-
scrollBottom();
|
|
228
|
-
|
|
229
|
-
fetch('/shell/run', {
|
|
230
|
-
method: 'POST',
|
|
231
|
-
headers: { 'content-type': 'application/json' },
|
|
232
|
-
body: JSON.stringify({ command: command, cwd: currentCwd })
|
|
233
|
-
})
|
|
234
|
-
.then(function (r) { return r.json(); })
|
|
235
|
-
.then(function (data) {
|
|
236
|
-
var out = document.createElement('div');
|
|
237
|
-
out.className = (data.ok === false && data.code !== 0) ? 'out err' : 'out';
|
|
238
|
-
out.textContent = data.output;
|
|
239
|
-
term.insertBefore(out, meta);
|
|
240
|
-
if (data.cwd && data.cwd !== currentCwd) {
|
|
241
|
-
currentCwd = data.cwd;
|
|
242
|
-
meta.innerHTML = infoHtml();
|
|
243
|
-
}
|
|
244
|
-
scrollBottom();
|
|
245
|
-
})
|
|
246
|
-
.catch(function (error) {
|
|
247
|
-
var out = document.createElement('div');
|
|
248
|
-
out.className = 'out err';
|
|
249
|
-
out.textContent = '请求失败:' + error.message;
|
|
250
|
-
term.insertBefore(out, meta);
|
|
251
|
-
scrollBottom();
|
|
252
|
-
})
|
|
253
|
-
.then(function () { input.focus(); });
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
input.addEventListener('input', function () {
|
|
257
|
-
autosize();
|
|
258
|
-
clearTimeout(input.__t);
|
|
259
|
-
input.__t = setTimeout(fetchComplete, 250);
|
|
260
|
-
});
|
|
261
|
-
input.addEventListener('keydown', function (event) {
|
|
262
|
-
// 回车提交统一在下面"Ctrl 两态"那段处理(那里还要判断 Ctrl 是否按下),这里不再重复绑定
|
|
263
|
-
if (event.key === 'Enter' && !event.shiftKey) event.preventDefault();
|
|
264
|
-
});
|
|
265
|
-
document.getElementById('tabkey').addEventListener('click', function (event) {
|
|
266
|
-
event.preventDefault();
|
|
267
|
-
completeNow();
|
|
268
|
-
input.focus();
|
|
269
|
-
});
|
|
270
|
-
document.getElementById('reset').addEventListener('click', function () {
|
|
271
|
-
fetch('/shell/run', {
|
|
272
|
-
method: 'POST',
|
|
273
|
-
headers: { 'content-type': 'application/json' },
|
|
274
|
-
body: JSON.stringify({ reset: true, cwd: currentCwd })
|
|
275
|
-
}).then(function () { location.reload(); });
|
|
276
|
-
});
|
|
277
|
-
|
|
278
|
-
/* ---------- 历史命令:↑ ↓ ---------- */
|
|
279
|
-
var history = [];
|
|
280
|
-
var histIndex = -1; // -1 表示不在浏览历史中
|
|
281
|
-
function rememberHistory(command) {
|
|
282
|
-
if (command.trim() === '') return;
|
|
283
|
-
if (history[history.length - 1] !== command) history.push(command);
|
|
284
|
-
if (history.length > 200) history.shift();
|
|
285
|
-
histIndex = -1;
|
|
286
|
-
}
|
|
287
|
-
document.getElementById('histUp').addEventListener('click', function (event) {
|
|
288
|
-
event.preventDefault();
|
|
289
|
-
if (history.length === 0) return;
|
|
290
|
-
histIndex = histIndex < 0 ? history.length - 1 : Math.max(0, histIndex - 1);
|
|
291
|
-
input.value = history[histIndex];
|
|
292
|
-
placeCaretEnd();
|
|
293
|
-
autosize();
|
|
294
|
-
input.focus();
|
|
295
|
-
});
|
|
296
|
-
document.getElementById('histDown').addEventListener('click', function (event) {
|
|
297
|
-
event.preventDefault();
|
|
298
|
-
if (history.length === 0) return;
|
|
299
|
-
if (histIndex < 0) return;
|
|
300
|
-
histIndex += 1;
|
|
301
|
-
if (histIndex >= history.length) {
|
|
302
|
-
histIndex = -1;
|
|
303
|
-
input.value = '';
|
|
304
|
-
} else {
|
|
305
|
-
input.value = history[histIndex];
|
|
306
|
-
}
|
|
307
|
-
placeCaretEnd();
|
|
308
|
-
autosize();
|
|
309
|
-
input.focus();
|
|
310
|
-
});
|
|
311
|
-
function placeCaretEnd() {
|
|
312
|
-
try {
|
|
313
|
-
input.setSelectionRange(input.value.length, input.value.length);
|
|
314
|
-
} catch (error) { /* 忽略 */ }
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/* ---------- Ctrl:两态按钮(默认抬起) ---------- */
|
|
318
|
-
var ctrlButton = document.getElementById('ctrlkey');
|
|
319
|
-
var ctrlHint = document.getElementById('ctrlhint');
|
|
320
|
-
var ctrlLatched = false;
|
|
321
|
-
function setCtrl(latched) {
|
|
322
|
-
ctrlLatched = latched;
|
|
323
|
-
ctrlButton.classList.toggle('pressed', latched);
|
|
324
|
-
ctrlButton.setAttribute('aria-pressed', latched ? 'true' : 'false');
|
|
325
|
-
ctrlButton.textContent = latched ? 'Ctrl ●' : 'Ctrl';
|
|
326
|
-
ctrlHint.textContent = latched ? 'Ctrl 已按下:再按 C 中断 / L 清屏 / D 重置 / U 清空 / A 行首 / E 行尾' : '';
|
|
327
|
-
}
|
|
328
|
-
ctrlButton.addEventListener('click', function (event) {
|
|
329
|
-
event.preventDefault();
|
|
330
|
-
setCtrl(!ctrlLatched);
|
|
331
|
-
input.focus();
|
|
332
|
-
});
|
|
333
|
-
|
|
334
|
-
function appendLine(html) {
|
|
335
|
-
var el = document.createElement('div');
|
|
336
|
-
el.innerHTML = html;
|
|
337
|
-
term.insertBefore(el, meta);
|
|
338
|
-
scrollBottom();
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// Ctrl+C:中断(杀掉当前命令并重启会话)
|
|
342
|
-
function interrupt() {
|
|
343
|
-
appendLine('<div class="out err">^C(正在中断…)</div>');
|
|
344
|
-
fetch('/shell/run', {
|
|
345
|
-
method: 'POST',
|
|
346
|
-
headers: { 'content-type': 'application/json' },
|
|
347
|
-
body: JSON.stringify({ interrupt: true, cwd: currentCwd })
|
|
348
|
-
})
|
|
349
|
-
.then(function (r) { return r.json(); })
|
|
350
|
-
.then(function (data) {
|
|
351
|
-
appendLine('<div class="out">' + esc(data.output || '(已中断)') + '</div>');
|
|
352
|
-
if (data.cwd) { currentCwd = data.cwd; meta.innerHTML = infoHtml(); }
|
|
353
|
-
})
|
|
354
|
-
.catch(function (error) {
|
|
355
|
-
appendLine('<div class="out err">中断失败:' + esc(error.message) + '</div>');
|
|
356
|
-
})
|
|
357
|
-
.then(function () { input.focus(); });
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// Ctrl+L:清屏(保留输入行)
|
|
361
|
-
function clearScreen() {
|
|
362
|
-
Array.prototype.slice.call(term.children).forEach(function (child) {
|
|
363
|
-
if (child === meta || child === form || child.id === 'cands' || child.id === 'ctrlhint') return;
|
|
364
|
-
if (child.contains(meta) || child.contains(form)) return;
|
|
365
|
-
child.remove();
|
|
366
|
-
});
|
|
367
|
-
scrollBottom();
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// Ctrl+D:重置会话
|
|
371
|
-
function resetSession() {
|
|
372
|
-
fetch('/shell/run', {
|
|
373
|
-
method: 'POST',
|
|
374
|
-
headers: { 'content-type': 'application/json' },
|
|
375
|
-
body: JSON.stringify({ reset: true, cwd: currentCwd })
|
|
376
|
-
}).then(function () { location.reload(); });
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
function handleCtrlKey(letter) {
|
|
380
|
-
var key = String(letter).toLowerCase();
|
|
381
|
-
if (key === 'c') { interrupt(); return true; }
|
|
382
|
-
if (key === 'l') { clearScreen(); return true; }
|
|
383
|
-
if (key === 'd') { resetSession(); return true; }
|
|
384
|
-
if (key === 'u') { input.value = ''; autosize(); return true; }
|
|
385
|
-
if (key === 'a') { try { input.setSelectionRange(0, 0); } catch (e) {} return true; }
|
|
386
|
-
if (key === 'e') { placeCaretEnd(); return true; }
|
|
387
|
-
return false;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// 键盘:Ctrl 按下时拦截字母;Ctrl+Enter 也可以直接提交
|
|
391
|
-
input.addEventListener('keydown', function (event) {
|
|
392
|
-
if (ctrlLatched && /^[a-zA-Z]$/u.test(event.key)) {
|
|
393
|
-
event.preventDefault();
|
|
394
|
-
if (handleCtrlKey(event.key)) {
|
|
395
|
-
setCtrl(false);
|
|
396
|
-
if (event.key.toLowerCase() !== 'c' && event.key.toLowerCase() !== 'd') input.focus();
|
|
397
|
-
}
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
if (event.key === 'Enter' && !event.shiftKey) {
|
|
401
|
-
event.preventDefault();
|
|
402
|
-
if (form.requestSubmit) form.requestSubmit();
|
|
403
|
-
else form.dispatchEvent(new Event('submit', { cancelable: true }));
|
|
404
|
-
}
|
|
405
|
-
});
|
|
406
|
-
|
|
407
|
-
var vv = window.visualViewport;
|
|
408
|
-
if (vv) {
|
|
409
|
-
var fit = function () {
|
|
410
|
-
document.body.style.height = vv.height + 'px';
|
|
411
|
-
scrollBottom();
|
|
412
|
-
};
|
|
413
|
-
vv.addEventListener('resize', fit);
|
|
414
|
-
vv.addEventListener('scroll', fit);
|
|
415
|
-
fit();
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
setCtrl(false);
|
|
419
|
-
autosize();
|
|
420
|
-
input.focus();
|
|
421
|
-
scrollBottom();
|
|
422
|
-
})();
|
|
423
|
-
</script>`
|
|
424
|
-
return `<!doctype html>
|
|
425
|
-
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
426
|
-
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
427
|
-
<title>终端 · DSH</title>
|
|
428
|
-
<style>${STYLE}</style></head>
|
|
429
|
-
<body>${body}</body></html>`
|
|
430
|
-
}
|